Programs & Examples On #Language detection

Language detection or language identification is the task of identifying the language(s) in a fragment of text.

How to mark-up phone numbers?

Using jQuery, replace all US telephone numbers on the page with the appropriate callto: or tel: schemes.

// create a hidden iframe to receive failed schemes
$('body').append('<iframe name="blackhole" style="display:none"></iframe>');

// decide which scheme to use
var scheme = (navigator.userAgent.match(/mobile/gi) ? 'tel:' : 'callto:');

// replace all on the page
$('article').each(function (i, article) {
    findAndReplaceDOMText(article, {
        find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
        replace:function (portion) {
            var a = document.createElement('a');
            a.className = 'telephone';
            a.href = scheme + portion.text.replace(/\D/g, '');
            a.textContent = portion.text;
            a.target = 'blackhole';
            return a;
        }
    });
});

Thanks to @jonas_jonas for the idea. Requires the excellent findAndReplaceDOMText function.

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

How can I convert JSON to a HashMap using Gson?

With google's Gson 2.7 (probably earlier versions too, but I tested with the current version 2.7) it's as simple as:

Map map = gson.fromJson(jsonString, Map.class);

Which returns a Map of type com.google.gson.internal.LinkedTreeMap and works recursively on nested objects, arrays, etc.

I ran the OP example like so (simply replaced double- with single-quotes and removed whitespace):

String jsonString = "{'header': {'alerts': [{'AlertID': '2', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}, {'AlertID': '3', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}], 'session': '0bc8d0835f93ac3ebbf11560b2c5be9a'}, 'result': '4be26bc400d3c'}";
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map.getClass().toString());
System.out.println(map);

And got the following output:

class com.google.gson.internal.LinkedTreeMap
{header={alerts=[{AlertID=2, TSExpires=null, Target=1, Text=woot, Type=1}, {AlertID=3, TSExpires=null, Target=1, Text=woot, Type=1}], session=0bc8d0835f93ac3ebbf11560b2c5be9a}, result=4be26bc400d3c}

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Merge development branch with master

Explanation from the bottom for ones who came here without any knowledge of branches.

Basic master branch development logic is: You work only on another branches and use master only to merge another branches.

You begin to create a new branch in this way:

  1. Clone repository in your local dir (or create a new repository):
$ cd /var/www
$ git clone [email protected]:user_name/repository_name.git
  1. Create a new branch. It will contain the latest files of your master branch repository
$ git branch new_branch
  1. Change your current git branch to the new_branch
$ git checkout new_branch
  1. Do coding, commits, as usual…
$ git add .
$ git commit -m “Initial commit”
$ git push # pushes commits only to “new_branch”
  1. When job is finished on this branch, merge with “master” branch:
$ git merge master
$ git checkout master # goes to master branch
$ git merge development # merges files in localhost. Master shouldn’t have any  commits ahead, otherwise there will be a need for pull and merging code by hands!
$ git push # pushes all “new_branch” commits to both branches - “master” and “new_branch”

I also recommend using the Sourcetree App to see visual tree of changes and branches.

How do I do an initial push to a remote repository with Git?

On server:

mkdir my_project.git
cd my_project.git
git --bare init

On client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

Note that when you add the origin, there are several formats and schemas you could use. I recommend you see what your hosting service provides.

Remove padding from columns in Bootstrap 3

Remove spacing from b/w columns using bootstrap 3.7.7 or less.

.no-gutter is a custom class that you can add to your row DIVs

.no-gutter > [class*='col-'] {
        padding-right:0;
        padding-left:0;
    }

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

How does Django's Meta class work?

You are asking a question about two different things:

  1. Meta inner class in Django models:

    This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.

    Short explanation is here: Django docs: Models: Meta options

    List of available meta options is here: Django docs: Model Meta options

    For latest version of Django: Django docs: Model Meta options

  2. Metaclass in Python:

    The best description is here: What are metaclasses in Python?

How do I create a Bash alias?

If you put blah="/usr/bin/blah" in your ~/.bashrc then you can use $blah in your login shell as a substitute for typing /usr/bin/blah

Android Studio does not show layout preview

Go to style.xml file and just add "Base" class before theme. as like

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
</style>

@Note: Replace Theme.AppCompat.Light.DarkActionBar to Base.Theme.AppCompat.Light.DarkActionBar

and clear project.

Date format in the json output using spring boot

You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.

You should do two things

  • add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Your module is not yet loaded by the Angular Server in node ng serve, so restart your server so the server loads the module that you just added in @NgModule app.module.ts

Base64 Encoding Image

My synopsis of rfc2397 is:

Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64," this is similar to the prefixing done in the parenthesis of url() definition in CSS or in the quoted value of the src attribute of the img tag in [X]HTML. You can test the data url in firefox by putting the data:image/... line into the URL field and pressing enter, it should show your image.

For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.

  1. Use the base64 command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
  2. Use a tool that features the option to convert to base64, like Notepad++ which has the feature under plugins->MIME tools->base64 Encode
  3. Email yourself the file and view the raw email contents, copy and paste.
  4. Use a web form.

A note on mime-types: I would prefer you use one of image/png image/jpeg or image/gif as I can't find the popular image/x-icon. Should that be image/vnd.microsoft.icon? Also the other formats are much shorter.

compare 265 bytes vs 1150 bytes:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=

data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==

CSS Div stretch 100% page height

It's simple using a table:

<html>

<head>
    <title>100% Height test</title>
</head>

<body>
    <table style="float: left; height: 100%; width: 200px; border: 1px solid red">
        <tbody>
            <tr>
                <td>Nav area</td>
            </tr>
        </tbody>
    </table>
    <div style="border: 1px solid green;">Content blabla... text
        <br /> text
        <br /> text
        <br /> text
        <br />
    </div>
</body>

</html>

When DIV was introduced, people were so afraid of tables that the poor DIV became the metaphorical hammer.

Get output parameter value in ADO.NET

string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);

//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;

//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);

//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “@EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);

//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();

//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}

Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output

How to convert String to DOM Document object in java?

Either escape the double quotes with \

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

or use single quotes instead

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

Why use @PostConstruct?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.

  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

how to write an array to a file Java

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
    Files.write( // write to file
        Paths.get(fileName), // get path from file
        Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
        Charset.forName("UTF-8") // formatting
    );
}

How to disassemble a memory range with GDB?

If all that you want is to see the disassembly with the INTC call, use objdump -d as someone mentioned but use the -static option when compiling. Otherwise the fopen function is not compiled into the elf and is linked at runtime.

Combine or merge JSON on node.js without jQuery

Lodash is a another powerful tool-belt option for these sorts of utilities. See: _.merge() (which is recursive)

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
}; 
_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } 

Are HTTPS URLs encrypted?

I agree with the previous answers:

To be explicit:

With TLS, the first part of the URL (https://www.example.com/) is still visible as it builds the connection. The second part (/herearemygetparameters/1/2/3/4) is protected by TLS.

However there are a number of reasons why you should not put parameters in the GET request.

First, as already mentioned by others: - leakage through browser address bar - leakage through history

In addition to that you have leakage of URL through the http referer: user sees site A on TLS, then clicks a link to site B. If both sites are on TLS, the request to site B will contain the full URL from site A in the referer parameter of the request. And admin from site B can retrieve it from the log files of server B.)

404 Not Found The requested URL was not found on this server

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

I am sure your issue will be solved...

How to succinctly write a formula with many variables from a data frame?

I build this solution, reformulate does not take care if variable names have white spaces.

add_backticks = function(x) {
    paste0("`", x, "`")
}

x_lm_formula = function(x) {
    paste(add_backticks(x), collapse = " + ")
}

build_lm_formula = function(x, y){
    if (length(y)>1){
        stop("y needs to be just one variable")
    }
    as.formula(        
        paste0("`",y,"`", " ~ ", x_lm_formula(x))
    )
}

# Example
df <- data.frame(
    y = c(1,4,6), 
    x1 = c(4,-1,3), 
    x2 = c(3,9,8), 
    x3 = c(4,-4,-2)
    )

# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"

# Run Model
lm(formula = formula, data = df)
# output
Call:
    lm(formula = formula, data = df)

Coefficients:
    (Intercept)           x1           x2           x3  
        -5.6316       0.7895       1.1579           NA  

```

Using print statements only to debug

First off, I will second the nomination of python's logging framework. Be a little careful about how you use it, however. Specifically: let the logging framework expand your variables, don't do it yourself. For instance, instead of:

logging.debug("datastructure: %r" % complex_dict_structure)

make sure you do:

logging.debug("datastructure: %r", complex_dict_structure)

because while they look similar, the first version incurs the repr() cost even if it's disabled. The second version avoid this. Similarly, if you roll your own, I'd suggest something like:

def debug_stdout(sfunc):
    print(sfunc())

debug = debug_stdout

called via:

debug(lambda: "datastructure: %r" % complex_dict_structure)

which will, again, avoid the overhead if you disable it by doing:

def debug_noop(*args, **kwargs):
    pass

debug = debug_noop

The overhead of computing those strings probably doesn't matter unless they're either 1) expensive to compute or 2) the debug statement is in the middle of, say, an n^3 loop or something. Not that I would know anything about that.

Gson - convert from Json to a typed ArrayList<T>

If you want convert from Json to a typed ArrayList , it's wrong to specify the type of the object contained in the list. The correct syntax is as follows:

 Gson gson = new Gson(); 
 List<MyClass> myList = gson.fromJson(inputString, ArrayList.class);

ZIP file content type for HTTP request

The standard MIME type for ZIP files is application/zip. The types for the files inside the ZIP does not matter for the MIME type.

As always, it ultimately depends on your server setup.

How to compare types

Try the following

typeField == typeof(string)
typeField == typeof(DateTime)

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.

Module is not available, misspelled or forgot to load (but I didn't)

I had the same error but i resolved it, it was a syntax error in the AngularJS provider

How to run a bash script from C++ program

The only standard mandated implementation dependent way is to use the system() function from stdlib.h.

Also if you know how to make user become the super-user that would be nice also.

Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo but there are a few things you need to know before you can go off using sudo.

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

javascript - match string against the array of regular expressions

http://jsfiddle.net/9nyhh/1/

var thisExpressions = [/something/, /something_else/, /and_something_else/];
var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray(string, expressions) {

    var len = expressions.length,
        i = 0;

    for (; i < len; i++) {
        if (string.match(expressions[i])) {
            return true;
        }
    }

    return false;

};

setTimeout(function() {
    console.log(matchInArray(thisString, thisExpressions));
    console.log(matchInArray(thisString, thisExpressions2));
}, 200)?

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.

How can I detect window size with jQuery?

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
<script>
    var WindowsSize=function(){
        var h=$(window).height(),
            w=$(window).width();
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
    };
   $(document).ready(WindowsSize); 
   $(window).resize(WindowsSize); 
</script>

Here is a snippet:

_x000D_
_x000D_
var WindowsSize=function(){_x000D_
     var h=$(window).height(),_x000D_
      w=$(window).width();_x000D_
     $("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
 };_x000D_
 $(document).ready(WindowsSize); _x000D_
 $(window).resize(WindowsSize); 
_x000D_
#winSize{_x000D_
  position:fixed;_x000D_
  bottom:1%;_x000D_
  right:1%;_x000D_
  border:rgba(0,0,0,0.8) 3px solid;_x000D_
  background:rgba(0,0,0,0.6);_x000D_
  padding:5px 10px;_x000D_
  color:#fff;_x000D_
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
  z-index:9999_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="winSize"></div>
_x000D_
_x000D_
_x000D_

Of course, adapt it to fit your needs! ;)

Add and remove attribute with jquery

If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.

var el = $("#page_navigation1");

$("#add").click(function(){
  el.attr("id","page_navigation1");
});     

$("#remove").click(function(){
  el.removeAttr("id");
});     

How to get first N number of elements from an array

Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.

In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like

var items = list
             .filter((i, index) => (index < 3))
             .map((i, index) => {
                   return (
                     <myview item={i} key={i.id} />
                   );
              });

Java: how can I split an ArrayList in multiple small ArrayLists?

Java 8

We can split a list based on some size or based on a condition.

static Collection<List<Integer>> partitionIntegerListBasedOnSize(List<Integer> inputList, int size) {
        return inputList.stream()
                .collect(Collectors.groupingBy(s -> (s-1)/size))
                .values();
}
static <T> Collection<List<T>> partitionBasedOnSize(List<T> inputList, int size) {
        final AtomicInteger counter = new AtomicInteger(0);
        return inputList.stream()
                    .collect(Collectors.groupingBy(s -> counter.getAndIncrement()/size))
                    .values();
}
static <T> Collection<List<T>> partitionBasedOnCondition(List<T> inputList, Predicate<T> condition) {
        return inputList.stream().collect(Collectors.partitioningBy(s-> (condition.test(s)))).values();
}

Then we can use them as:

final List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
System.out.println(partitionIntegerListBasedOnSize(list, 4));  // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
System.out.println(partitionBasedOnSize(list, 4));  // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
System.out.println(partitionBasedOnSize(list, 3));  // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
System.out.println(partitionBasedOnCondition(list, i -> i<6));  // [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]

Changing a specific column name in pandas DataFrame

A one liner does exist:

In [27]: df=df.rename(columns = {'two':'new_name'})

In [28]: df
Out[28]: 
  one three  new_name
0    1     a         9
1    2     b         8
2    3     c         7
3    4     d         6
4    5     e         5

Following is the docstring for the rename method.

Definition: df.rename(self, index=None, columns=None, copy=True, inplace=False)
Docstring:
Alter index and / or columns using input function or
functions. Function / dict values must be unique (1-to-1). Labels not
contained in a dict / Series will be left as-is.

Parameters
----------
index : dict-like or function, optional
    Transformation to apply to index values
columns : dict-like or function, optional
    Transformation to apply to column values
copy : boolean, default True
    Also copy underlying data
inplace : boolean, default False
    Whether to return a new DataFrame. If True then value of copy is
    ignored.

See also
--------
Series.rename

Returns
-------
renamed : DataFrame (new object)

Conditional Formatting (IF not empty)

In Excel 2003 you should be able to create a formatting rule like:

=A1<>"" and then drag/copy this to other cells as needed.

If that doesn't work, try =Len(A1)>0.

If there may be spaces in the cell which you will consider blank, then do:

=Len(Trim(A1))>0

Let me know if you can't get any of these to work. I have an old machine running XP and Office 2003, I can fire it up to troubleshoot if needed.

Call to undefined function mysql_query() with Login

You are mixing mysql and mysqli

Change these lines:

$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);

to

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

How to check if a string contains text from an array of substrings in JavaScript?

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}

ProcessStartInfo hanging on "WaitForExit"? Why?

I was having the same issue, but the reason was different. It would however happen under Windows 8, but not under Windows 7. The following line seems to have caused the problem.

pProcess.StartInfo.UseShellExecute = False

The solution was to NOT disable UseShellExecute. I now received a Shell popup window, which is unwanted, but much better than the program waiting for nothing particular to happen. So I added the following work-around for that:

pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

Now the only thing bothering me is to why this is happening under Windows 8 in the first place.

What is the "-->" operator in C/C++?

Why all the complication?

The simple answer to the original question is just:

#include <stdio.h>

int main()
{
    int x = 10;
    while (x > 0)
    {
        printf("%d ", x);
        x = x-1;
    }
}

It does the same thing. I am not saying you should do it like this, but it does the same thing and would have answered the question in one post.

The x-- is just shorthand for the above, and > is just a normal greater-than operator. No big mystery!

There are too many people making simple things complicated nowadays ;)

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

How to remove selected commit log entries from a Git repository while keeping their changes?

git-rebase(1) does exactly that.

$ git rebase -i HEAD~5

git awsome-ness [git rebase --interactive] contains an example.

  1. Don't use git-rebase on public (remote) commits.
  2. Make sure your working directory is clean (commit or stash your current changes).
  3. Run the above command. It launches your $EDITOR.
  4. Replace pick before C and D by squash. It will meld C and D into B. If you want to delete a commit then just delete its line.

If you are lost, type:

$ git rebase --abort  

How can I add a hint text to WPF textbox?

Do it in the code-behind by setting the text color initially to gray and adding event handlers for gaining and losing keyboard focus.

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);

Then the event handlers:

private void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if(sender is TextBox)
    {
        //If nothing has been entered yet.
        if(((TextBox)sender).Foreground == Brushes.Gray)
        {
            ((TextBox)sender).Text = "";
            ((TextBox)sender).Foreground = Brushes.Black;
        }
    }
}


private void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    //Make sure sender is the correct Control.
    if(sender is TextBox)
    {
        //If nothing was entered, reset default text.
        if(((TextBox)sender).Text.Trim().Equals(""))
        {
            ((TextBox)sender).Foreground = Brushes.Gray;
            ((TextBox)sender).Text = "Text";
        }
    }
}

Python Socket Receive Large Amount of Data

Modifying Adam Rosenfield's code:

import sys


def send_msg(sock, msg):
    size_of_package = sys.getsizeof(msg)
    package = str(size_of_package)+":"+ msg #Create our package size,":",message
    sock.sendall(package)

def recv_msg(sock):
    try:
        header = sock.recv(2)#Magic, small number to begin with.
        while ":" not in header:
            header += sock.recv(2) #Keep looping, picking up two bytes each time

        size_of_package, separator, message_fragment = header.partition(":")
        message = sock.recv(int(size_of_package))
        full_message = message_fragment + message
        return full_message

    except OverflowError:
        return "OverflowError."
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise

I would, however, heavily encourage using the original approach.

How to make a div with no content have a width?

Try to add display:block; to your test1

Scraping html tables into R data frames using the XML package

…or a shorter try:

library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

the picked table is the longest one on the page

tables[[which.max(n.rows)]]

header('HTTP/1.0 404 Not Found'); not doing anything

You could try specifying an HTTP response code using an optional parameter:

header('HTTP/1.0 404 Not Found', true, 404);

Get MIME type from filename extension

This helper class returns mime type (content type), description and icons for any file name:

using Microsoft.Win32;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;

public static class Helper
{
    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    private static extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phIconLarge, IntPtr[] phIconSmall, int nIcons);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern int DestroyIcon(IntPtr hIcon);

    public static string GetFileContentType(string fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        RegistryKey registryKey = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return string.Empty;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey == null)
            {
                return string.Empty;
            }

            object contentTypeObject = registryKey.GetValue("Content Type");
            if (!(contentTypeObject is string))
            {
                return string.Empty;
            }

            string contentType = (string)contentTypeObject;

            return contentType;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            if (registryKey != null)
            {
                registryKey.Close();
            }
        }
    }

    public static string GetFileDescription(string fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        RegistryKey registryKey1 = null;
        RegistryKey registryKey2 = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return string.Empty;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey1 = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey1 == null)
            {
                return string.Empty;
            }

            object extensionDefaultObject = registryKey1.GetValue(null);
            if (!(extensionDefaultObject is string))
            {
                return string.Empty;
            }

            string extensionDefaultValue = (string)extensionDefaultObject;

            registryKey2 = Registry.ClassesRoot.OpenSubKey(extensionDefaultValue);
            if (registryKey2 == null)
            {
                return string.Empty;
            }

            object fileDescriptionObject = registryKey2.GetValue(null);
            if (!(fileDescriptionObject is string))
            {
                return string.Empty;
            }

            string fileDescription = (string)fileDescriptionObject;
            return fileDescription;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            if (registryKey2 != null)
            {
                registryKey2.Close();
            }

            if (registryKey1 != null)
            {
                registryKey1.Close();
            }
        }
    }

    public static void GetFileIcons(string fileName, out Icon smallIcon, out Icon largeIcon)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        smallIcon = null;
        largeIcon = null;

        RegistryKey registryKey1 = null;
        RegistryKey registryKey2 = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey1 = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey1 == null)
            {
                return;
            }

            object extensionDefaultObject = registryKey1.GetValue(null);
            if (!(extensionDefaultObject is string))
            {
                return;
            }

            string defaultIconKeyName = string.Format("{0}\\DefaultIcon", extensionDefaultObject);

            registryKey2 = Registry.ClassesRoot.OpenSubKey(defaultIconKeyName);
            if (registryKey2 == null)
            {
                return;
            }

            object defaultIconPathObject = registryKey2.GetValue(null);
            if (!(defaultIconPathObject is string))
            {
                return;
            }

            string defaultIconPath = (string)defaultIconPathObject;
            if (string.IsNullOrWhiteSpace(defaultIconPath))
            {
                return;
            }

            string iconfileName = null;
            int iconIndex = 0;

            int commaIndex = defaultIconPath.IndexOf(",");
            if (commaIndex > 0)
            {
                iconfileName = defaultIconPath.Substring(0, commaIndex);
                string iconIndexString = defaultIconPath.Substring(commaIndex + 1);

                if (!int.TryParse(iconIndexString, out iconIndex))
                {
                    iconIndex = 0;
                }
            }
            else
            {
                iconfileName = defaultIconPath;
                iconIndex = 0;
            }

            IntPtr[] phiconSmall = new IntPtr[1] { IntPtr.Zero };
            IntPtr[] phiconLarge = new IntPtr[1] { IntPtr.Zero };

            int readIconCount = ExtractIconEx(iconfileName, iconIndex, phiconLarge, phiconSmall, 1);

            if (readIconCount < 0)
            {
                return;
            }

            if (phiconSmall[0] != IntPtr.Zero)
            {
                smallIcon = (Icon)Icon.FromHandle(phiconSmall[0]).Clone();
                DestroyIcon(phiconSmall[0]);
            }

            if (phiconLarge[0] != IntPtr.Zero)
            {
                largeIcon = (Icon)Icon.FromHandle(phiconLarge[0]).Clone();
                DestroyIcon(phiconLarge[0]);
            }

            return;
        }
        finally
        {
            if (registryKey2 != null)
            {
                registryKey2.Close();
            }

            if (registryKey1 != null)
            {
                registryKey1.Close();
            }
        }
    }
}

Usage:

string fileName = "NotExists.txt";
string contentType = Helper.GetFileContentType(fileName); // "text/plain"
string description = Helper.GetFileDescription(fileName); // "Text Document"
Icon smallIcon, largeIcon;
Helper.GetFileIcons(fileName, out smallIcon, out largeIcon); // 16x16, 32x32 icons

Serializing PHP object to JSON

Try using this, this worked fine for me.

json_encode(unserialize(serialize($array)));

splitting a string based on tab in the file

Python has support for CSV files in the eponymous csv module. It is relatively misnamed since it support much more that just comma separated values.

If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values...

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

It seems like You haven't set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it. Thank you. Happy learning!

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

Create GUI using Eclipse (Java)

Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):

enter image description here

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

What is the difference between aggregation, composition and dependency?

Containment :- Here to access inner object we have to use outer object. We can reuse the contained object. Aggregation :- Here we can access inner object again and again without using outer object.

ASP.Net which user account running Web Service on IIS 7?

You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs

The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs

and "check names" button

It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy

  • computername
  • Entire Directory
    • pdgs.local

So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"

Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline

click ok, allow full control, and click ok again.

That´s all folks, Hope it helps,

Jose from Moralzarzal ( Madrid )

making a paragraph in html contain a text from a file

Javascript will do the trick here.

function load() {
    var file = new XMLHttpRequest();
    file.open("GET", "http://remote.tld/random.txt", true);
    file.onreadystatechange = function() {
      if (file.readyState === 4) {  // Makes sure the document is ready to parse
        if (file.status === 200) {  // Makes sure it's found the file
          text = file.responseText;
          document.getElementById("div1").innerHTML = text;
        }
      }
    }
}

window.onLoad = load();

Getting the exception value in Python

Even though I realise this is an old question, I'd like to suggest using the traceback module to handle output of the exceptions.

Use traceback.print_exc() to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc() to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.

How to resize an image with OpenCV2.0 and Python2.6

def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_height` (preserving aspect ratio)."""
    w = int(round(target_height * image.shape[1] / image.shape[0]))
    return cv2.resize(image, (w, target_height), interpolation=method)

def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_width` (preserving aspect ratio)."""
    h = int(round(target_width * image.shape[0] / image.shape[1]))
    return cv2.resize(image, (target_width, h), interpolation=method)

How to load CSS Asynchronously

The function below will create and add to the document all the stylesheets that you wish to load asynchronously. (But, thanks to the Event Listener, it will only do so after all the window's other resources have loaded.)

See the following:

function loadAsyncStyleSheets() {

    var asyncStyleSheets = [
    '/stylesheets/async-stylesheet-1.css',
    '/stylesheets/async-stylesheet-2.css'
    ];

    for (var i = 0; i < asyncStyleSheets.length; i++) {
        var link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', asyncStyleSheets[i]);
        document.head.appendChild(link);
    }
}

window.addEventListener('load', loadAsyncStyleSheets, false);

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

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

How to install and run Typescript locally in npm?

To install TypeScript local in project as a development dependency you can use --save-dev key

npm install --save-dev typescript

It's also writes the typescript into your package.json

You also need to have a tsconfig.json file. For example

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    ".npm"
  ]
}

For more information about the tsconfig you can see here http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Catching multiple exception types in one catch block

Coming in PHP 7.1 is the ability to catch multiple types.

So that this:

<?php
try {
    /* ... */
} catch (FirstException $ex) {
    $this->manageException($ex);
} catch (SecondException $ex) {
    $this->manageException($ex);
}
?>

and

<?php
try {

} catch (FirstException | SecondException $ex) {
    $this->manageException($ex);
}
?>

are functionally equivalent.

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

View tabular file such as CSV from command line

I used pisswillis's answer for a long time.

csview()
{
    local file="$1"
    sed "s/,/\t/g" "$file" | less -S
}

But then combined some code I found at http://chrisjean.com/2011/06/17/view-csv-data-from-the-command-line which works better for me:

csview()
{
    local file="$1"
    cat "$file" | sed -e 's/,,/, ,/g' | column -s, -t | less -#5 -N -S
}

The reason it works better for me is that it handles wide columns better.

Eclipse fonts and background color

Switch to Theme... is also an option

enter image description here

How to take a screenshot programmatically on iOS

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *imageData = UIImageJPEGRepresentation(image, 1.0 ); //you can use PNG too
[imageData writeToFile:@"image1.jpeg" atomically:YES];

How can I delete a service in Windows?

Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):

SC STOP shortservicename
SC DELETE shortservicename

Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc is aliased to set-content. So sc delete service will actually create a file called delete with the content service. To do this in Powershell, use sc.exe delete service instead


If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:

SC QUERY state= all >"C:\Service List.txt"

For a more concise list, execute this command:

SC QUERY state= all | FIND "_NAME"

The short service name will be listed just above the display name, like this:

SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service

And thus to delete that service:

SC STOP MyService
SC DELETE MyService

How to add a JAR in NetBeans

Project Files Services Tabls

go files tabs

drag drop file to libs files hover.

return project tabs and what are you see :)

How do you truncate all tables in a database using TSQL?

select 'delete from ' +TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'

where result come.

Copy and paste on query window and run the command

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

How do I convert an existing callback API to promises?

The callback style function always like this(almost all function in node.js is this style):

//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))

This style has same feature:

  1. the callback function is passed by last argument.

  2. the callback function always accept the error object as it's first argument.

So, you could write a function for convert a function with this style like this:

const R =require('ramda')

/**
 * A convenient function for handle error in callback function.
 * Accept two function res(resolve) and rej(reject) ,
 * return a wrap function that accept a list arguments,
 * the first argument as error, if error is null,
 * the res function will call,else the rej function.
 * @param {function} res the function which will call when no error throw
 * @param {function} rej the function which will call when  error occur
 * @return {function} return a function that accept a list arguments,
 * the first argument as error, if error is null, the res function
 * will call,else the rej function
 **/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
    R.propEq('err', null),
    R.compose(
        res,
        R.prop('data')
    ),
    R.compose(
        rej,
        R.prop('err')
    )
)({err, data})

/**
 * wrap the callback style function to Promise style function,
 * the callback style function must restrict by convention:
 * 1. the function must put the callback function where the last of arguments,
 * such as (arg1,arg2,arg3,arg...,callback)
 * 2. the callback function must call as callback(err,arg1,arg2,arg...)
 * @param {function} fun the callback style function to transform
 * @return {function} return the new function that will return a Promise,
 * while the origin function throw a error, the Promise will be Promise.reject(error),
 * while the origin function work fine, the Promise will be Promise.resolve(args: array),
 * the args is which callback function accept
 * */
 const toPromise = (fun) => (...args) => new Promise(
    (res, rej) => R.apply(
        fun,
        R.append(
            checkErr(res, rej),
            args
        )
    )
)

For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply) and append(like javascript function.prototype.push ). So, we could convert the a callback style function to promise style function now:

const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
    .then(
        (files) => console.log(files),
        (err) => console.log(err)
    )

toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).

Hope this answer is useful for you.

How to create a private class method?

private doesn't seem to work if you are defining a method on an explicit object (in your case self). You can use private_class_method to define class methods as private (or like you described).

class Person
  def self.get_name
    persons_name
  end

  def self.persons_name
    "Sam"
  end

  private_class_method :persons_name
end

puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name

Alternatively (in ruby 2.1+), since a method definition returns a symbol of the method name, you can also use this as follows:

class Person
  def self.get_name
    persons_name
  end

  private_class_method def self.persons_name
    "Sam"
  end
end

puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name

How to get the PYTHONPATH in shell?

Python, at startup, loads a bunch of values into sys.path (which is "implemented" via a list of strings), including:

  • various hardcoded places
  • the value of $PYTHONPATH
  • probably some stuff from startup files (I'm not sure if Python has rcfiles)

$PYTHONPATH is only one part of the eventual value of sys.path.

If you're after the value of sys.path, the best way would be to ask Python (thanks @Codemonkey):

python -c "import sys; print sys.path"

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

Android: failed to convert @drawable/picture into a drawable

Also check if the resource-name contains any illegal characters (for me it was a "-" in my-image)

Why do we need to use flatMap?

It's not an array of arrays. It's an observable of observable(s).

The following returns an observable stream of string.

requestStream
  .map(function(requestUrl) {
    return requestUrl;
  });

While this returns an observable stream of observable stream of json

requestStream
  .map(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

flatMap flattens the observable automatically for us so we can observe the json stream directly

How do I calculate the date in JavaScript three months prior to today?

To make things really simple you can use DateJS, a date library for JavaScript:

http://www.datejs.com/

Example code for you:

Date.today().add({ months: -1 });

How to check if an user is logged in Symfony2 inside a controller?

It's good practise to extend from a baseController and implement some base functions implement a function to check if the user instance is null like this if the user form the Userinterface then there is no user logged in

/**

*/
class BaseController extends AbstractController
{

    /**
     * @return User

     */
    protected function getUser(): ?User
    {
        return parent::getUser();
    }

    /**
     * @return bool
     */
    protected function isUserLoggedIn(): bool
    {
        return $this->getUser() instanceof User;
    }
}

How to find the last field using 'cut'

There are multiple ways. You may use this too.

echo "Your string here"| tr ' ' '\n' | tail -n1
> here

Obviously, the blank space input for tr command should be replaced with the delimiter you need.

Customize list item bullets using CSS

Another way of changing the size of the bullets would be:

  1. Disabling the bullets altogether
  2. Re-adding the custom bullets with the help of ::before pseudo-element.

Example:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
  display:          inline-block;_x000D_
  vertical-align:   middle;_x000D_
  width:            5px;_x000D_
  height:           5px;_x000D_
  background-color: #000000;_x000D_
  margin-right:     8px;_x000D_
  content:          ' '_x000D_
}
_x000D_
<ul>_x000D_
  <li>first element</li>_x000D_
  <li>second element</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

No markup changes needed

Complex JSON nesting of objects and arrays

I successfully solved my problem. Here is my code:

The complex JSON object:

   {
    "medications":[{
            "aceInhibitors":[{
                "name":"lisinopril",
                "strength":"10 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "antianginal":[{
                "name":"nitroglycerin",
                "strength":"0.4 mg Sublingual Tab",
                "dose":"1 tab",
                "route":"SL",
                "sig":"q15min PRN",
                "pillCount":"#30",
                "refills":"Refill 1"
            }],
            "anticoagulants":[{
                "name":"warfarin sodium",
                "strength":"3 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "betaBlocker":[{
                "name":"metoprolol tartrate",
                "strength":"25 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "diuretic":[{
                "name":"furosemide",
                "strength":"40 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "mineral":[{
                "name":"potassium chloride ER",
                "strength":"10 mEq Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }]
        }
    ],
    "labs":[{
        "name":"Arterial Blood Gas",
        "time":"Today",
        "location":"Main Hospital Lab"      
        },
        {
        "name":"BMP",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BNP",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BUN",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Cardiac Enzymes",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"CBC",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Creatinine",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"Electrolyte Panel",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Glucose",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"PT/INR",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"PTT",
        "time":"3 Weeks",
        "location":"Coumadin Clinic"    
        },
        {
        "name":"TSH",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        }
    ],
    "imaging":[{
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        }
    ]
}

The jQuery code to grab the data and display it on my webpage:

$(document).ready(function() {
var items = [];

$.getJSON('labOrders.json', function(json) {
  $.each(json.medications, function(index, orders) {
    $.each(this, function() {
        $.each(this, function() {
            items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
        });
    });
  });

  $('<div>', {
    "class":'loaded',
    html:items.join('')
  }).appendTo("body");

});

});

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

fstream won't create a file

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

Save base64 string as PDF at client side with JavaScript

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xls or .zip file. You just need to change file name to fileName.xls or fileName.zip. This depends on your case.

setImmediate vs. nextTick

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

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

How to return a value from a Form in C#?

I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.

Android Studio shortcuts like Eclipse

These are some of the useful shortcuts for Android studio (Windows)

  • Double Shift - Search EveryWhere

  • Ctrl + Shift+A - quick command search

  • Ctrl +N - Find Class (capable of finding internall classes aswell)

  • Ctrl +Shift+N - Find File

  • Alt+F7 - Find Uses (To get the call hierarchy)

  • Ctrl+B - goto class definition.

  • Ctrl+LeftClick - goto to symbol(variable, method, class) definition/definition.

  • Ctrl+Alt+Left - Back

  • Ctrl+Alt+Right - Right

  • Shift+f6 - Refactor/Rename

Play multiple CSS animations at the same time

you can try something like this

set the parent to rotate and the image to scale so that the rotate and scale time can be different

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
}_x000D_
.image {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: scale 4s linear infinite;_x000D_
}_x000D_
@-webkit-keyframes spin {_x000D_
  100% {_x000D_
    transform: rotate(180deg);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes scale {_x000D_
  100% {_x000D_
    transform: scale(2);_x000D_
  }_x000D_
}
_x000D_
<div>_x000D_
  <img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.');

Max or Default?

For Entity Framework and Linq to SQL we can achieve this by defining an extension method which modifies an Expression passed to IQueryable<T>.Max(...) method:

static class Extensions
{
    public static TResult MaxOrDefault<T, TResult>(this IQueryable<T> source, 
                                                   Expression<Func<T, TResult>> selector)
        where TResult : struct
    {
        UnaryExpression castedBody = Expression.Convert(selector.Body, typeof(TResult?));
        Expression<Func<T, TResult?>> lambda = Expression.Lambda<Func<T,TResult?>>(castedBody, selector.Parameters);
        return source.Max(lambda) ?? default(TResult);
    }
}

Usage:

int maxId = dbContextInstance.Employees.MaxOrDefault(employee => employee.Id);
// maxId is equal to 0 if there is no records in Employees table

The generated query is identical, it works just like a normal call to IQueryable<T>.Max(...) method, but if there is no records it returns a default value of type T instead of throwing an exeption

Firing events on CSS class changes in jQuery

You can bind the DOMSubtreeModified event. I add an example here:

HTML

<div id="mutable" style="width:50px;height:50px;">sjdfhksfh<div>
<div>
  <button id="changeClass">Change Class</button>
</div>

JavaScript

$(document).ready(function() {
  $('#changeClass').click(function() {
    $('#mutable').addClass("red");
  });

  $('#mutable').bind('DOMSubtreeModified', function(e) {
      alert('class changed');
  });
});

http://jsfiddle.net/hnCxK/13/

How can I get the full/absolute URL (with domain) in Django?

If you don't want to hit the database, you could do it with a setting. Then, use a context processor to add it to every template:

# settings.py (Django < 1.9)
...
BASE_URL = 'http://example.com'
TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.extra_context',
)
# settings.py (Django >= 1.9)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Additional
                'myapp.context_processors.extra_context',
            ],
        },
    },
]

# myapp/context_processors.py
from django.conf import settings

def extra_context(request):
    return {'base_url': settings.BASE_URL}

# my_template.html
<p>Base url is {{ base_url }}.</p>

"No such file or directory" error when executing a binary

The answer is in this line of the output of readelf -a in the original question

  [Requesting program interpreter: /lib/ld-linux.so.2]

I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.

Where do you include the jQuery library from? Google JSAPI? CDN?

In head:

  (function() {
    var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
    jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
  })();

End of Body:

<script type="text/javascript">
google.load("jquery", "version");
</script>

What do *args and **kwargs mean?

Also, we use them for managing inheritance.

class Super( object ):
   def __init__( self, this, that ):
       self.this = this
       self.that = that

class Sub( Super ):
   def __init__( self, myStuff, *args, **kw ):
       super( Sub, self ).__init__( *args, **kw )
       self.myStuff= myStuff

x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )

This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

Determining the version of Java SDK on the Mac

In /System/Library/Frameworks/JavaVM.framework/Versions you'll see all the installed JDKs. There is a symbolic link named CurrentJDK pointing the active JDK.

Powershell folder size of folders without listing Subdirectories

At the answer from @squicc if you amend this line: $topDir = Get-ChildItem -directory "C:\test" with -force then you will be able to see the hidden directories also. Without this, the size will be different when you run the solution from inside or outside the folder.

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

window.history.length (Integer)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

Lets say a user visits your page, clicks on some links and goes back:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

window.goBack = function (e){
    var defaultLocation = "http://www.mysite.com";
    var oldHash = window.location.hash;

    history.back(); // Try to go back

    var newHash = window.location.hash;

    /* If the previous page hasn't been loaded in a given time (in this case
    * 1000ms) the user is redirected to the default location given above.
    * This enables you to redirect the user to another page.
    *
    * However, you should check whether there was a referrer to the current
    * site. This is a good indicator for a previous entry in the history
    * session.
    *
    * Also you should check whether the old location differs only in the hash,
    * e.g. /index.html#top --> /index.html# shouldn't redirect to the default
    * location.
    */

    if(
        newHash === oldHash &&
        (typeof(document.referrer) !== "string" || document.referrer  === "")
    ){
        window.setTimeout(function(){
            // redirect to default location
            window.location.href = defaultLocation;
        },1000); // set timeout in ms
    }
    if(e){
        if(e.preventDefault)
            e.preventDefault();
        if(e.preventPropagation)
            e.preventPropagation();
    }
    return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

See also:

Android, How to create option Menu

Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate(). Hope this will help you out.

Difference between hamiltonian path and euler path

An Euler path is a path that uses every edge of a graph exactly once.and it must have exactly two odd vertices.the path starts and ends at different vertex. A Hamiltonian cycle is a cycle that contains every vertex of the graph hence you may not use all the edges of the graph.

Convert SVG to image (JPEG, PNG, etc.) in the browser

change svg to match your element

function svg2img(){
    var svg = document.querySelector('svg');
    var xml = new XMLSerializer().serializeToString(svg);
    var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
    var b64start = 'data:image/svg+xml;base64,';
    var image64 = b64start + svg64;
    return image64;
};svg2img()

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

Resizing SVG in html?

Here is an example of getting the bounds using svg.getBox(): https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.

 // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);

Unable to generate an explicit migration in entity framework

In my case, I forgot to add my IP address in firewall rules in Azure, basically as I was unable to connect to the database I was getting this error. So specifically for my case, I added my IP address in database firewall rules in Azure and it all worked well. Apart from this, it could be the issue of proxy/internet connection/DB username password/DB connection string etc. OR obviously, you might have pending migrations for which you need to run Update-Database command.

How to execute my SQL query in CodeIgniter

$this->db->select('id, name, price, author, category, language, ISBN, publish_date');

       $this->db->from('tbl_books');

How to make a <ul> display in a horizontal row

You could also set them to float to the right.

#ul_top_hypers li {
    float: right;
}

This allows them to still be block level, but will appear on the same line.

Is there a method that calculates a factorial in Java?

You can use recursion version as well.

static int myFactorial(int i) {
    if(i == 1)
        return;
    else
        System.out.prinln(i * (myFactorial(--i)));
}

Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.

Open text file and program shortcut in a Windows batch file

Its very simple, 1)Just go on directory where the file us stored 2)then enter command i.e. type filename.file_extention e.g type MyFile.tx

Is a view faster than a simple query?

There should be some trivial gain in having the execution plan stored, but it will be negligible.

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

SELECT where row value contains string MySQL

My suggestion would be

$value = $_POST["myfield"];

$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

Difference between r+ and w+ in fopen()

This diagram will be faster to read next time. Maybe someone else will find that helpful too. This is clearly explained the difference between. enter image description here

How to properly -filter multiple strings in a PowerShell copy script

Something like this should work (it did for me). The reason for wanting to use -Filter instead of -Include is that include takes a huge performance hit compared to -Filter.

Below just loops each file type and multiple servers/workstations specified in separate files.

##  
##  This script will pull from a list of workstations in a text file and search for the specified string


## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside

$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'

##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'

foreach ($server in $servers)
    {

    foreach ($filetype in $filetypes)
    {

    ## below creates the search path.  This could be further improved to exclude the windows directory
    $serverString = "\\"+$server+"\c$\Program Files"


    ## Display the server being queried
    write-host “Server:” $server "searching for " $filetype in $serverString

    Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
    #-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
    Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt

    $os = gwmi win32_operatingsystem -computer $server
    $sp = $os | % {$_.servicepackmajorversion}
    $a = $os | % {$_.caption}

    ##  Below will list again the server name as well as its OS and SP
    ##  Because the script may not be monitored, this helps confirm the machine has been successfully scanned
        write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp


    }

}
#end script

Check if a time is between two times (time DataType)

WITH CTE as
(
SELECT CAST(ShiftStart AS DATETIME) AS ShiftStart, 
CASE WHEN ShiftStart > ShiftEnd THEN CAST(ShiftEnd AS DATETIME) +1
ELSE CAST(ShiftEnd AS DATETIME) END AS ShiftEnd
FROM **TABLE_NAME**
)
SELECT * FROM CTE
WHERE 
CAST('11:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- Start of Shift
OR CAST('23:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- End of Shift

"The semaphore timeout period has expired" error for USB connection

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

How to find if a native DLL file is compiled as x64 or x86?

I rewrote c++ solution in first answer in powershell script. Script can determine this types of .exe and .dll files:

#Description       C# compiler switch             PE type       machine corflags
#MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
#MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
#x86 mixed         n/a                            PE32  x86     32BITREQUIRED
#x64 managed       /platform:x64                  PE32+ x64     ILONLY
#x64 mixed         n/a                            PE32+ x64  
#ARM managed       /platform:arm                  PE32  ARM     ILONLY
#ARM mixed         n/a                            PE32  ARM  

this solution has some advantages over corflags.exe and loading assembly via Assembly.Load in C# - you will never get BadImageFormatException or message about invalid header.

function GetActualAddressFromRVA($st, $sec, $numOfSec, $dwRVA)
{
    [System.UInt32] $dwRet = 0;
    for($j = 0; $j -lt $numOfSec; $j++)   
    {   
        $nextSectionOffset = $sec + 40*$j;
        $VirtualSizeOffset = 8;
        $VirtualAddressOffset = 12;
        $SizeOfRawDataOffset = 16;
        $PointerToRawDataOffset = 20;

    $Null = @(
        $curr_offset = $st.BaseStream.Seek($nextSectionOffset + $VirtualSizeOffset, [System.IO.SeekOrigin]::Begin);        
        [System.UInt32] $VirtualSize = $b.ReadUInt32();
        [System.UInt32] $VirtualAddress = $b.ReadUInt32();
        [System.UInt32] $SizeOfRawData = $b.ReadUInt32();
        [System.UInt32] $PointerToRawData = $b.ReadUInt32();        

        if ($dwRVA -ge $VirtualAddress -and $dwRVA -lt ($VirtualAddress + $VirtualSize)) {
            $delta = $VirtualAddress - $PointerToRawData;
            $dwRet = $dwRVA - $delta;
            return $dwRet;
        }
        );
    }
    return $dwRet;
}

function Get-Bitness2([System.String]$path, $showLog = $false)
{
    $Obj = @{};
    $Obj.Result = '';
    $Obj.Error = $false;

    $Obj.Log = @(Split-Path -Path $path -Leaf -Resolve);

    $b = new-object System.IO.BinaryReader([System.IO.File]::Open($path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read, [System.IO.FileShare]::Read));
    $curr_offset = $b.BaseStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin)
    [System.Int32] $peOffset = $b.ReadInt32();
    $Obj.Log += 'peOffset ' + "{0:X0}" -f $peOffset;

    $curr_offset = $b.BaseStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $peHead = $b.ReadUInt32();

    if ($peHead -ne 0x00004550) {
        $Obj.Error = $true;
        $Obj.Result = 'Bad Image Format';
        $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
    };

    if ($Obj.Error)
    {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    [System.UInt16] $machineType = $b.ReadUInt16();
    $Obj.Log += 'machineType ' + "{0:X0}" -f $machineType;

    [System.UInt16] $numOfSections = $b.ReadUInt16();
    $Obj.Log += 'numOfSections ' + "{0:X0}" -f $numOfSections;
    if (($machineType -eq 0x8664) -or ($machineType -eq 0x200)) { $Obj.Log += 'machineType: x64'; }
    elseif ($machineType -eq 0x14c)                             { $Obj.Log += 'machineType: x86'; }
    elseif ($machineType -eq 0x1c0)                             { $Obj.Log += 'machineType: ARM'; }
    else{
        $Obj.Error = $true;
        $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Output ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    $curr_offset = $b.BaseStream.Seek($peOffset+20, [System.IO.SeekOrigin]::Begin);
    [System.UInt16] $sizeOfPeHeader = $b.ReadUInt16();

    $coffOffset = $peOffset + 24;#PE header size is 24 bytes
    $Obj.Log += 'coffOffset ' + "{0:X0}" -f $coffOffset;

    $curr_offset = $b.BaseStream.Seek($coffOffset, [System.IO.SeekOrigin]::Begin);#+24 byte magic number
    [System.UInt16] $pe32 = $b.ReadUInt16();         
    $clr20headerOffset = 0;
    $flag32bit = $false;
    $Obj.Log += 'pe32 magic number: ' + "{0:X0}" -f $pe32;
    $Obj.Log += 'size of optional header ' + ("{0:D0}" -f $sizeOfPeHeader) + " bytes";

    #COMIMAGE_FLAGS_ILONLY               =0x00000001,
    #COMIMAGE_FLAGS_32BITREQUIRED        =0x00000002,
    #COMIMAGE_FLAGS_IL_LIBRARY           =0x00000004,
    #COMIMAGE_FLAGS_STRONGNAMESIGNED     =0x00000008,
    #COMIMAGE_FLAGS_NATIVE_ENTRYPOINT    =0x00000010,
    #COMIMAGE_FLAGS_TRACKDEBUGDATA       =0x00010000,
    #COMIMAGE_FLAGS_32BITPREFERRED       =0x00020000,

    $COMIMAGE_FLAGS_ILONLY        = 0x00000001;
    $COMIMAGE_FLAGS_32BITREQUIRED = 0x00000002;
    $COMIMAGE_FLAGS_32BITPREFERRED = 0x00020000;

    $offset = 96;
    if ($pe32 -eq 0x20b) {
        $offset = 112;#size of COFF header is bigger for pe32+
    }     

    $clr20dirHeaderOffset = $coffOffset + $offset + 14*8;#clr directory header offset + start of section number 15 (each section is 8 byte long);
    $Obj.Log += 'clr20dirHeaderOffset ' + "{0:X0}" -f $clr20dirHeaderOffset;
    $curr_offset = $b.BaseStream.Seek($clr20dirHeaderOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $clr20VirtualAddress = $b.ReadUInt32();
    [System.UInt32] $clr20Size = $b.ReadUInt32();
    $Obj.Log += 'clr20VirtualAddress ' + "{0:X0}" -f $clr20VirtualAddress;
    $Obj.Log += 'clr20SectionSize ' + ("{0:D0}" -f $clr20Size) + " bytes";

    if ($clr20Size -eq 0) {
        if ($machineType -eq 0x1c0) { $Obj.Result = 'ARM native'; }
        elseif ($pe32 -eq 0x10b)    { $Obj.Result = '32-bit native'; }
        elseif($pe32 -eq 0x20b)     { $Obj.Result = '64-bit native'; }

       $b.Close();   
       if ($Obj.Result -eq '') { 
            $Obj.Error = $true;
            $Obj.Log += 'Unknown type of file';
       }
       else { 
            if ($showLog) { Write-Output ($Obj.Log | Format-List | Out-String); };
            return $Obj.Result;
       }
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    [System.UInt32]$sectionsOffset = $coffOffset + $sizeOfPeHeader;
    $Obj.Log += 'sectionsOffset ' + "{0:X0}" -f $sectionsOffset;
    $realOffset = GetActualAddressFromRVA $b $sectionsOffset $numOfSections $clr20VirtualAddress;
    $Obj.Log += 'real IMAGE_COR20_HEADER offset ' + "{0:X0}" -f $realOffset;
    if ($realOffset -eq 0) {
        $Obj.Error = $true;
        $Obj.Log += 'cannot find COR20 header - exit with error';
        $b.Close();
        return $false;
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    $curr_offset = $b.BaseStream.Seek($realOffset + 4, [System.IO.SeekOrigin]::Begin);
    [System.UInt16] $majorVer = $b.ReadUInt16();
    [System.UInt16] $minorVer = $b.ReadUInt16();
    $Obj.Log += 'IMAGE_COR20_HEADER version ' + ("{0:D0}" -f $majorVer) + "." + ("{0:D0}" -f $minorVer);

    $flagsOffset = 16;#+16 bytes - flags field
    $curr_offset = $b.BaseStream.Seek($realOffset + $flagsOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $flag32bit = $b.ReadUInt32();
    $Obj.Log += 'CorFlags: ' + ("{0:X0}" -f $flag32bit);

#Description       C# compiler switch             PE type       machine corflags
#MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
#MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
#x86 mixed         n/a                            PE32  x86     32BITREQUIRED
#x64 managed       /platform:x64                  PE32+ x64     ILONLY
#x64 mixed         n/a                            PE32+ x64  
#ARM managed       /platform:arm                  PE32  ARM     ILONLY
#ARM mixed         n/a                            PE32  ARM  

    $isILOnly = ($flag32bit -band $COMIMAGE_FLAGS_ILONLY) -eq $COMIMAGE_FLAGS_ILONLY;
    $Obj.Log += 'ILONLY: ' + $isILOnly;
    if ($machineType -eq 0x1c0) {#if ARM
        if ($isILOnly) { $Obj.Result = 'ARM managed'; } 
                  else { $Obj.Result = 'ARM mixed'; }
    }
    elseif ($pe32 -eq 0x10b) {#pe32
        $is32bitRequired = ($flag32bit -band $COMIMAGE_FLAGS_32BITREQUIRED) -eq $COMIMAGE_FLAGS_32BITREQUIRED;
        $is32bitPreffered = ($flag32bit -band $COMIMAGE_FLAGS_32BITPREFERRED) -eq $COMIMAGE_FLAGS_32BITPREFERRED;
        $Obj.Log += '32BIT: ' + $is32bitRequired;    
        $Obj.Log += '32BIT PREFFERED: ' + $is32bitPreffered 
        if     ($is32bitRequired  -and $isILOnly  -and $is32bitPreffered) { $Obj.Result = 'AnyCpu 32bit-preffered'; }
        elseif ($is32bitRequired  -and $isILOnly  -and !$is32bitPreffered){ $Obj.Result = 'x86 managed'; }
        elseif (!$is32bitRequired -and !$isILOnly -and $is32bitPreffered) { $Obj.Result = 'x86 mixed'; }
        elseif ($isILOnly)                                                { $Obj.Result = 'AnyCpu'; }
   }
   elseif ($pe32 -eq 0x20b) {#pe32+
        if ($isILOnly) { $Obj.Result = 'x64 managed'; } 
                  else { $Obj.Result = 'x64 mixed'; }
   }

   $b.Close();   
   if ($showLog) { Write-Host ($Obj.Log | Format-List | Out-String); }
   if ($Obj.Result -eq ''){ return 'Unknown type of file';};
   $flags = '';
   if ($isILOnly) {$flags += 'ILONLY';}
   if ($is32bitRequired) {
        if ($flags -ne '') {$flags += ' | ';}
        $flags += '32BITREQUIRED';
   }
   if ($is32bitPreffered) {
        if ($flags -ne '') {$flags += ' | ';}
        $flags += '32BITPREFERRED';
   }
   if ($flags -ne '') {$flags = ' (' + $flags +')';}
   return $Obj.Result + $flags;
}

usage example:

#$filePath = "C:\Windows\SysWOW64\regedit.exe";#32 bit native on 64bit windows
$filePath = "C:\Windows\regedit.exe";#64 bit native on 64bit windows | should be 32 bit native on 32bit windows

Get-Bitness2 $filePath $true;

you can omit second parameter if you don't need to see details

Java: Find .txt files in specified folder

import org.apache.commons.io.FileUtils;   

List<File> htmFileList = new ArrayList<File>();

for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
    htmFileList.add(file);
}

This is my latest code to add all text files from a directory

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

Configuring RollingFileAppender in log4j

Toolbear74 is right log4j.XML is required. In order to get the XML to validate the <param> tags need to be BEFORE the <rollingPolicy> I suggest setting a logging threshold <param name="threshold" value="info"/>

When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.

Here is an example:

<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
  <appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
     <param name="threshold" value="info"/>
     <rollingPolicy name="file"  
                      class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" 
               value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
        <param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
     </rollingPolicy>
     <layout class="org.apache.log4j.EnhancedPatternLayout" >
        <param name="ConversionPattern" 
               value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value="debug"></priority>
    <appender-ref ref="file" />
  </root>
</log4j:configuration>

Considering that your setting a FileNamePattern and an ActiveFileName I think that setting a File property is redundant and possibly even erroneous

Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

There is a library that provides a better ProcessBuilder, zt-exec. This library can do exactly what you are asking for and more.

Here's what your code would look like with zt-exec instead of ProcessBuilder :

add the dependency :

<dependency>
  <groupId>org.zeroturnaround</groupId>
  <artifactId>zt-exec</artifactId>
  <version>1.11</version>
</dependency>

The code :

new ProcessExecutor()
  .command("somecommand", "arg1", "arg2")
  .redirectOutput(System.out)
  .redirectError(System.err)
  .execute();

Documentation of the library is here : https://github.com/zeroturnaround/zt-exec/

Controller 'ngModel', required by directive '...', can't be found

You can also remove the line

  require: 'ngModel',

if you don't need ngModel in this directive. Removing ngModel will allow you to make a directive without thatngModel error.

Import .bak file to a database in SQL server

You can simply restore these database backup files using native SQL Server methods, or you can use ApexSQL Restore tool to quickly virtually attach the files and access them as fully restored databases.

Disclaimer: I work as a Product Support Engineer at ApexSQL

How do you convert a jQuery object into a string?

It may be possible to use the jQuery.makeArray(obj) utility function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

How to change an Android app's name?

There's the android:label for the application, and the android:label for the launch activity. The former is what you see under Settings -> Applications -> Manage Applications on your device. The latter is what you see under Applications, and by extension in any shortcut to your application, e.g.

<application
    android:label="@string/turns_up_in_manage_apps" >
    <activity
        android:name=".MainActivity"
        android:label="@string/turns_up_in_shortcuts" >
        ...
    </activity>
</application>

How can I load webpage content into a div on page load?

You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.

How to get row count in an Excel file using POI library?

Sheet.getPhysicalNumberOfRows() does not involve some empty rows. If you want to loop for all rows, do not use this to know the loop size.

How to read a line from the console in C?

A very simple but unsafe implementation to read line for static allocation:

char line[1024];

scanf("%[^\n]", line);

A safer implementation, without the possibility of buffer overflow, but with the possibility of not reading the whole line, is:

char line[1024];

scanf("%1023[^\n]", line);

Not the 'difference by one' between the length specified declaring the variable and the length specified in the format string. It is a historical artefact.

Classes vs. Modules in VB.NET

It is acceptable to use Module. Module is not used as a replacement for Class. Module serves its own purpose. The purpose of Module is to use as a container for

  • extension methods,
  • variables that are not specific to any Class, or
  • variables that do not fit properly in any Class.

Module is not like a Class since you cannot

  • inherit from a Module,
  • implement an Interface with a Module,
  • nor create an instance of a Module.

Anything inside a Module can be directly accessed within the Module assembly without referring to the Module by its name. By default, the access level for a Module is Friend.

Formatting doubles for output in C#

Though this question is meanwhile closed, I believe it is worth mentioning how this atrocity came into existence. In a way, you may blame the C# spec, which states that a double must have a precision of 15 or 16 digits (the result of IEEE-754). A bit further on (section 4.1.6) it's stated that implementations are allowed to use higher precision. Mind you: higher, not lower. They are even allowed to deviate from IEEE-754: expressions of the type x * y / z where x * y would yield +/-INF but would be in a valid range after dividing, do not have to result in an error. This feature makes it easier for compilers to use higher precision in architectures where that'd yield better performance.

But I promised a "reason". Here's a quote (you requested a resource in one of your recent comments) from the Shared Source CLI, in clr/src/vm/comnumber.cpp:

"In order to give numbers that are both friendly to display and round-trippable, we parse the number using 15 digits and then determine if it round trips to the same value. If it does, we convert that NUMBER to a string, otherwise we reparse using 17 digits and display that."

In other words: MS's CLI Development Team decided to be both round-trippable and show pretty values that aren't such a pain to read. Good or bad? I'd wish for an opt-in or opt-out.

The trick it does to find out this round-trippability of any given number? Conversion to a generic NUMBER structure (which has separate fields for the properties of a double) and back, and then compare whether the result is different. If it is different, the exact value is used (as in your middle value with 6.9 - i) if it is the same, the "pretty value" is used.

As you already remarked in a comment to Andyp, 6.90...00 is bitwise equal to 6.89...9467. And now you know why 0.0...8818 is used: it is bitwise different from 0.0.

This 15 digits barrier is hard-coded and can only be changed by recompiling the CLI, by using Mono or by calling Microsoft and convincing them to add an option to print full "precision" (it is not really precision, but by the lack of a better word). It's probably easier to just calculate the 52 bits precision yourself or use the library mentioned earlier.

EDIT: if you like to experiment yourself with IEE-754 floating points, consider this online tool, which shows you all relevant parts of a floating point.

What is SuppressWarnings ("unchecked") in Java?

It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts. It essentially implies that the programmer did not wish to be notified about these which he is already aware of when compiling a particular bit of code.

You can read more on this specific annotation here:

SuppressWarnings

Additionally, Oracle provides some tutorial documentation on the usage of annotations here:

Annotations

As they put it,

"The 'unchecked' warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled Generics)."

What is the difference between SQL and MySQL?

SQL is Structured Query Language

MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>

...and:

@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */
}

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */
}

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

How to parse XML in Bash?

This is sufficient...

xpath xhtmlfile.xhtml '/html/head/title/text()' > titleOfXHTMLPage.txt

How do I show/hide a UIBarButtonItem?

Some helper methods I thought I'd share based upon lnafziger's accepted answer as I have multiple toolbars and multiple buttons in each:

-(void) hideToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    [toolbarButtons removeObject:button];
    [toolbar setItems:toolbarButtons animated:NO];
}

-(void) showToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar atIndex:(int) index{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    if (![toolbarButtons containsObject:button]){
        [toolbarButtons insertObject:button atIndex:index];
        [self setToolbarItems:toolbarButtons animated:YES];
    }
}

compareTo() vs. equals()

equals() checks whether two strings are equal or not.It gives boolean value. compareTo() checks whether string object is equal to,greater or smaller to the other string object.It gives result as : 1 if string object is greater 0 if both are equal -1 if string is smaller than other string

eq:

String a = "Amit";
String b = "Sumit";
String c = new String("Amit");
System.out.println(a.equals(c));//true
System.out.println(a.compareTo(c)); //0
System.out.println(a.compareTo(b)); //1

Access Database opens as read only

Create an empty folder and move the .mdb file to that folder. And try opening it from there. I tried it this way and it worked for me.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

How to disable a particular checkstyle rule for a particular line of code?

Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON

Or even better, use this more tweaked version:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
</module>

which allows you to turn off specific checks for specific lines of code:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

*Note: you'll also have to add the FileContentsHolder:

<module name="FileContentsHolder"/>

See also

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>
</module>

under the SuppressionFilter section on that same page, which allows you to turn off individual checks for pattern matched resources.

So, if you have in your checkstyle.xml:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>
</module>

You can turn it off in your suppression xml file with:

<suppress id="maxParameterNumber" files="YourCode.java"/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnings java annotation. To do this, you will need to add two new modules (SuppressWarningsFilter and SuppressWarningsHolder) in your configuration file:

<module name="Checker">
   ...
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       ...
       <module name="SuppressWarningsHolder" />
   </module>
</module> 

Then, within your code you can do the following:

@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {

or, for multiple suppressions:

@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {

NB: The "checkstyle:" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.

SQL Server: Is it possible to insert into two tables at the same time?

In one statement: No.

In one transaction: Yes

BEGIN TRANSACTION
   DECLARE @DataID int;
   INSERT INTO DataTable (Column1 ...) VALUES (....);
   SELECT @DataID = scope_identity();
   INSERT INTO LinkTable VALUES (@ObjectID, @DataID);
COMMIT

The good news is that the above code is also guaranteed to be atomic, and can be sent to the server from a client application with one sql string in a single function call as if it were one statement. You could also apply a trigger to one table to get the effect of a single insert. However, it's ultimately still two statements and you probably don't want to run the trigger for every insert.

Sending a file over TCP sockets in Python

Put file inside while True like so

while True:
     f = open('torecv.png','wb')
     c, addr = s.accept()     # Establish connection with client.
     print 'Got connection from', addr
     print "Receiving..."
     l = c.recv(1024)
     while (l):
         print "Receiving..."
         f.write(l)
         l = c.recv(1024)
     f.close()
     print "Done Receiving"
     c.send('Thank you for connecting')
     c.close()   

Remove all items from RecyclerView

On Xamarin.Android, It works for me and need change layout

 var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
 layout.SpanCount = GetItemPerRow(Context);
 recyclerView.SetAdapter(null);
 recyclerView.SetAdapter(adapter); //reset

How to fix "Headers already sent" error in PHP

I got this error many times before, and I am certain all PHP programmer got this error at least once before.

Possible Solution 1

This error may have been caused by the blank spaces before the start of the file or after the end of the file.These blank spaces should not be here.

ex) THERE SHOULD BE NO BLANK SPACES HERE

   echo "your code here";

?>
THERE SHOULD BE NO BLANK SPACES HERE

Check all files associated with file that causes this error.

Note: Sometimes EDITOR(IDE) like gedit (a default linux editor) add one blank line on save file. This should not happen. If you are using Linux. you can use VI editor to remove space/lines after ?> at the end of the page.

Possible Solution 2: If this is not your case, then use ob_start to output buffering:

<?php
  ob_start();

  // code 

 ob_end_flush();
?> 

This will turn output buffering on and your headers will be created after the page is buffered.

Python : List of dict, if exists increment a dict value, if not append a new dict

Using the default works, but so does:

urls[url] = urls.get(url, 0) + 1

using .get, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.

"static const" vs "#define" vs "enum"

It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:

  1. static const int var = 5;
  2. #define var 5
  3. enum { var = 5 };

Ignoring issues about the choice of name, then:

  • If you need to pass a pointer around, you must use (1).
  • Since (2) is apparently an option, you don't need to pass pointers around.
  • Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is.
  • (1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can.
  • (1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can.
  • Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5.
  • (1) cannot be used in places like switch statements; both (2) and (3) can.
  • (1) cannot be used to initialize static variables; both (2) and (3) can.
  • (2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that.
  • You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.

So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.

If you were asking about C++, then you'd use option (1) — the static const — every time.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Manually put files to Android emulator SD card

I am using Android Studio 3.3.

Go to View -> Tools Window -> Device File Explorer. Or you can find it on the Bottom Right corner of the Android Studio.

If the Emulator is running, the Device File Explorer will display the File structure on Emulator Storage.

Here you can right click on a Folder and select "Upload" to place the file

enter image description here

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Iterating over arrays in Python 3

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.

Set Radiobuttonlist Selected from Codebehind

Try this option:

radio1.Items.FindByValue("1").Selected = true;

How to Copy Text to Clip Board in Android?

Try the following code. It will support the latest API:

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                        if (clipboard.hasPrimaryClip()) {
                            android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
                            android.content.ClipData data = clipboard.getPrimaryClip();
                            if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
                            {
                                String url= (String) clipboard.getText();
                                searchText.setText(url);
                                System.out.println("data="+data+"description="+description+"url="+url);
                            }}

how to loop through json array in jquery?

var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function() {
  $.each(this, function(key, val){
    alert(val);//here data 
      alert (key); //here key

  });
});

How do I profile memory usage in Python?

Below is a simple function decorator which allows to track how much memory the process consumed before the function call, after the function call, and what is the difference:

import time
import os
import psutil
 
 
def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
 
 
def get_process_memory():
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    return mem_info.rss
 
 
def profile(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

Here is my blog which describes all the details. (archived link)

How to Check whether Session is Expired or not in asp.net

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

IIS Manager in Windows 10

Actually you must make sure that the IIS Management Console feature is explicitly checked. On my win 10 pro I had to do it manually, checking the root only was not enough!

How to convert base64 string to image?

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)

Then somewhere in your code you can use it like this:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How can JavaScript save to a local file?

If you are using FireFox you can use the File HandleAPI

https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API

I had just tested it out and it works!

Find row in datatable with specific id

Try avoiding unnecessary loops and go for this if needed.

string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
    //your logic goes here
}
else
{
    //your logic goes here
}

If you want to search by specific ID then there should be a primary key in a table.

JavaScript to get rows count of a HTML table

$('tableName').find('tr').length

Convert list of dictionaries to a pandas DataFrame

The easiest way I have found to do it is like this:

dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)

How to get URL parameter using jQuery or plain JavaScript?

This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:

function urlParam(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    // Need to decode the URL parameters, including putting in a fix for the plus sign
    // https://stackoverflow.com/a/24417399
    return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Is there a job scheduler library for node.js?

You can use timexe

It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.

Install:

npm install timexe

Use:

var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });

(I'm the author)

What is sharding and why is it important?

Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.

Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)

How to delete an SMS from the inbox in Android programmatically?

I think this can not be perfectly done for the time being. There are 2 basic problems:

  1. How can you make sure the sms is already in the inbox when you try to delete it?
    Notice that SMS_RECEIVED is not an ordered broadcast.
    So dmyung's solution is completely trying one's luck; even the delay in Doug's answer is not a guarantee.

  2. The SmsProvider is not thread safe.(refer to http://code.google.com/p/android/issues/detail?id=2916#c0)
    The fact that more than one clients are requesting delete and insert in it at the same time will cause data corruption or even immediate Runtime Exception.

Swift - how to make custom header for UITableView?

If you are willing to use custom table header as table header, try the followings....

Updated for swift 3.0

Step 1

Create UITableViewHeaderFooterView for custom header..

import UIKit

class MapTableHeaderView: UITableViewHeaderFooterView {

    @IBOutlet weak var testView: UIView!

}

Step 2

Add custom header to UITableView

    override func viewDidLoad() {
            super.viewDidLoad()

            tableView.delegate = self
            tableView.dataSource = self

            //register the header view

            let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
            self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")


    }

    extension BranchViewController : UITableViewDelegate{

    }

    extension BranchViewController : UITableViewDataSource{

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 200
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView

            return headerView
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: 

    Int) -> Int {
            // retuen no of rows in sections
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
            // retuen your custom cells    
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        }

        func numberOfSections(in tableView: UITableView) -> Int {
            // retuen no of sections
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            // retuen height of row
        }


    }

How to get file URL using Storage facade in laravel 5?

Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).

However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.

By this way, you have full access for functions that you need like getPublicUrl() in order to get the public URL from a cdn container:

/** @var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');

// $url:  https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);

In conclusion, if need to take storage service to another level, then flysystem is not enough. For local purposes, you can try @nXu's solution

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How can I get the session object if I have the entity-manager?

See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:

Session session = entityManager.unwrap(Session.class);

Alter table add multiple columns ms sql

ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage  bit,
     HasPhotoInWorkStorage  bit,
     HasPhotoInMaterialStorage bit *(Missing ,)*
     HasText  bit);

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx