Programs & Examples On #Helpermethods

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.

What REALLY happens when you don't free after malloc?

I think that your two examples are actually only one: the free() should occur only at the end of the process, which as you point out is useless since the process is terminating.

In you second example though, the only difference is that you allow an undefined number of malloc(), which could lead to running out of memory. The only way to handle the situation is to check the return code of malloc() and act accordingly.

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

How do I redirect to another webpage?

Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.


To just redirect to a page with JavaScript:

window.location.href = "/contact/";

Or if you need a delay:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.

$('a,img').on('click',function(e){
  e.preventDefault();
  $(this).animate({
    opacity: 0 //Put some CSS animation here
  }, 500);
  setTimeout(function(){
    // OK, finished jQuery staff, let's go redirect
    window.location.href = "/contact/";
  },500);
});

Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.

Different names of JSON property during serialization and deserialization

This was not what I was expecting as a solution (though it is a legitimate use case). My requirement was to allow an existing buggy client (a mobile app which already released) to use alternate names.

The solution lies in providing a separate setter method like this:

@JsonSetter( "r" )
public void alternateSetRed( byte red ) {
    this.red = red;
}

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.

You need to use a Theme.AppCompat theme (or descendant) with this activity

I had an activity with theme <android:theme="@android:style/Theme.Dialog"> used for showing dialog in my appWidget and i had same problem

i solved this error by changing activity code like below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_AppCompat_Dialog); //this line i added
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dialog);
}

Getting the length of two-dimensional array

Assuming that the length is same for each array in the second dimension, you can use

public class B {    
 public static void main(String [] main){
    int [] [] nir= new int [2] [3];
    System.out.println(nir[0].length);
 }
}

Convert seconds into days, hours, minutes and seconds

This is a function i used in the past for substracting a date from another one related with your question, my principe was to get how many days, hours minutes and seconds has left until a product has expired :

$expirationDate = strtotime("2015-01-12 20:08:23");
$toDay = strtotime(date('Y-m-d H:i:s'));
$difference = abs($toDay - $expirationDate);
$days = floor($difference / 86400);
$hours = floor(($difference - $days * 86400) / 3600);
$minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
$seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);

echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";

C# string replace

Use of the replace() method

Here I'm replacing an old value to a new value:

string actual = "Hello World";

string Result = actual.Replace("World", "Stack Overflow");

----------------------
Output : "Hello Stack Overflow"

Fastest way to write huge data in text file Java

You might try removing the BufferedWriter and just using the FileWriter directly. On a modern system there's a good chance you're just writing to the drive's cache memory anyway.

It takes me in the range of 4-5 seconds to write 175MB (4 million strings) -- this is on a dual-core 2.4GHz Dell running Windows XP with an 80GB, 7200-RPM Hitachi disk.

Can you isolate how much of the time is record retrieval and how much is file writing?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class FileWritingPerfTest {
    

private static final int ITERATIONS = 5;
private static final double MEG = (Math.pow(1024, 2));
private static final int RECORD_COUNT = 4000000;
private static final String RECORD = "Help I am trapped in a fortune cookie factory\n";
private static final int RECSIZE = RECORD.getBytes().length;

public static void main(String[] args) throws Exception {
    List<String> records = new ArrayList<String>(RECORD_COUNT);
    int size = 0;
    for (int i = 0; i < RECORD_COUNT; i++) {
        records.add(RECORD);
        size += RECSIZE;
    }
    System.out.println(records.size() + " 'records'");
    System.out.println(size / MEG + " MB");
    
    for (int i = 0; i < ITERATIONS; i++) {
        System.out.println("\nIteration " + i);
        
        writeRaw(records);
        writeBuffered(records, 8192);
        writeBuffered(records, (int) MEG);
        writeBuffered(records, 4 * (int) MEG);
    }
}

private static void writeRaw(List<String> records) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        System.out.print("Writing raw... ");
        write(records, writer);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void writeBuffered(List<String> records, int bufSize) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(writer, bufSize);
    
        System.out.print("Writing buffered (buffer size: " + bufSize + ")... ");
        write(records, bufferedWriter);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void write(List<String> records, Writer writer) throws IOException {
    long start = System.currentTimeMillis();
    for (String record: records) {
        writer.write(record);
    }
    // writer.flush(); // close() should take care of this
    writer.close(); 
    long end = System.currentTimeMillis();
    System.out.println((end - start) / 1000f + " seconds");
}
}

Jar mismatch! Fix your dependencies

Remove android-support-v4.jar file from the libs folder from your project.

Join/Where with LINQ and Lambda

1 equals 1 two different table join

var query = from post in database.Posts
            join meta in database.Post_Metas on 1 equals 1
            where post.ID == id
            select new { Post = post, Meta = meta };

Callback when CSS3 transition finishes

Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.

Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:

$("#element").click( function () {
    $('#element').transition({ opacity: 0 }, function () { $(this).remove(); });
});

JS Fiddle Demo

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

How can I add an item to a IEnumerable<T> collection?

In .net Core, there is a method Enumerable.Append that does exactly that.

The source code of the method is available on GitHub..... The implementation (more sophisticated than the suggestions in other answers) is worth a look :).

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.

if it doesnt take you to the file, then add the name of the file to the urs. like this:

   https://127.0.0.1:8887/fileName.txt

link to web server for chrome: click me

Datatable select method ORDER BY clause

You can use the below simple method of sorting:

datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";

By the above method, you will be able to sort N number of columns.

Apache Prefork vs Worker MPM

For CentOS 6.x and 7.x (including Amazon Linux) use:

sudo httpd -V

This will show you which of the MPMs are configured. Either prefork, worker, or event. Prefork is the earlier, threadsafe model. Worker is multi-threaded, and event supports php-mpm which is supposed to be a better system for handling threads and requests.

However, your results may vary, based on configuration. I've seen a lot of instability in php-mpm and not any speed improvements. An aggressive spider can exhaust the maximum child processes in php-mpm quite easily.

The setting for prefork, worker, or event is set in sudo nano /etc/httpd/conf.modules.d/00-mpm.conf (for CentOS 6.x/7.x/Apache 2.4).

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#LoadModule mpm_event_module modules/mod_mpm_event.so

Is Fortran easier to optimize than C for heavy calculations?

I'm a hobbyist programmer and i'm "average" at both language. I find it easier to write fast Fortran code than C (or C++) code. Both Fortran and C are "historic" languages (by today standard), are heavily used, and have well supported free and commercial compiler.

I don't know if it's an historic fact but Fortran feel like it's built to be paralleled/distributed/vectorized/whatever-many-cores-ized. And today it's pretty much the "standard metric" when we're talking about speed : "does it scale ?"

For pure cpu crunching i love Fortran. For anything IO related i find it easier to work with C. (it's difficult in both case anyway).

Now of course, for parallel math intensive code you probably want to use your GPU. Both C and Fortran have a lot of more or less well integrated CUDA/OpenCL interface (and now OpenACC).

My moderately objective answer is : If you know both language equally well/poorly then i think Fortran is faster because i find it easier to write parallel/distributed code in Fortran than C. (once you understood that you can write "freeform" fortran and not just strict F77 code)

Here is a 2nd answer for those willing to downvote me because they don't like the 1st answer : Both language have the features required to write high-performance code. So it's dependent of the algorithm you're implementing (cpu intensive ? io intensive ? memory intensive?), the hardware (single cpu ? multi-core ? distribute supercomputer ? GPGPU ? FPGA ?), your skill and ultimately the compiler itself. Both C and Fortran have awesome compiler. (i'm seriously amazed by how advanced Fortran compilers are but so are C compilers).

PS : i'm glad you specifically excluded libs because i have a great deal of bad stuff to say about Fortran GUI libs. :)

Encoding conversion in java

CharsetDecoder should be what you are looking for, no ?

Many network protocols and files store their characters with a byte-oriented character set such as ISO-8859-1 (ISO-Latin-1).
However, Java's native character encoding is Unicode UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order).

See Charset. That doesn't mean UTF16 is the default charset (i.e.: the default "mapping between sequences of sixteen-bit Unicode code units and sequences of bytes"):

Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets.
[US-ASCII, ISO-8859-1 a.k.a. ISO-LATIN-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16]
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.

This example demonstrates how to convert ISO-8859-1 encoded bytes in a ByteBuffer to a string in a CharBuffer and visa versa.

// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
    // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
    // The new ByteBuffer is ready to be read.
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));

    // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    // The new ByteBuffer is ready to be read.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
} catch (CharacterCodingException e) {
}

How to set env variable in Jupyter notebook

If you're using Python, you can define your environment variables in a .env file and load them from within a Jupyter notebook using python-dotenv.

Install python-dotenv:

pip install python-dotenv

Load the .env file in a Jupyter notebook:

%load_ext dotenv
%dotenv

You don't have write permissions for the /var/lib/gems/2.3.0 directory

If you want to use the distribution Ruby instead of rb-env/rvm, you can set up a GEM_HOME for your current user. Start by creating a directory to store the Ruby gems for your user:

$ mkdir ~/.ruby

Then update your shell to use that directory for GEM_HOME and to update your PATH variable to include the Ruby gem bin directory.

$ echo 'export GEM_HOME=~/.ruby/' >> ~/.bashrc
$ echo 'export PATH="$PATH:~/.ruby/bin"' >> ~/.bashrc
$ source ~/.bashrc

(That last line will reload the environment variables in your current shell.)

Now you should be able to install Ruby gems under your user using the gem command. I was able to get this working with Ruby 2.5.1 under Ubuntu 18.04. If you are using a shell that is not Bash, then you will need to edit the startup script for that shell instead of bashrc.

Create controller for partial view in ASP.NET MVC

You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async

@await Html.PartialAsync("_LoginPartial")

or

@{await Html.RenderPartialAsync("PartialName");}

or if you are using .net core 2.1 > you can just use:

<partial name="Shared/_ProductPartial.cshtml"
         for="Product" />

Java - ignore exception and continue

LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

"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

Is there a way to make npm install (the command) to work behind proxy?

Use below command at cmd or GIT Bash or other prompt

$ npm config set proxy "http://192.168.1.101:4128"

$ npm config set https-proxy "http://192.168.1.101:4128"

where 192.168.1.101 is proxy ip and 4128 is port. change according to your proxy settings. its works for me.

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

Encrypt Password in Configuration Files?

Yes, definitely don't write your own algorithm. Java has lots of cryptography APIs.

If the OS you are installing upon has a keystore, then you could use that to store your crypto keys that you will need to encrypt and decrypt the sensitive data in your configuration or other files.

When should we use Observer and Observable?

Since Java9, both interfaces are deprecated, meaning you should not use them anymore. See Observer is deprecated in Java 9. What should we use instead of it?

However, you might still get interview questions about them...

How to avoid 'cannot read property of undefined' errors?

I answered this before and happened to be doing a similar check today. A simplification to check if a nested dotted property exists. You could modify this to return the value, or some default to accomplish your goal.

function containsProperty(instance, propertyName) {
    // make an array of properties to walk through because propertyName can be nested
    // ex "test.test2.test.test"
    let walkArr = propertyName.indexOf('.') > 0 ? propertyName.split('.') : [propertyName];

    // walk the tree - if any property does not exist then return false
    for (let treeDepth = 0, maxDepth = walkArr.length; treeDepth < maxDepth; treeDepth++) {

        // property does not exist
        if (!Object.prototype.hasOwnProperty.call(instance, walkArr[treeDepth])) {
            return false;
        }

        // does it exist - reassign the leaf
        instance = instance[walkArr[treeDepth]];

    }

    // default
    return true;

}

In your question you could do something like:

let test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
containsProperty(test[0], 'a.b.c');

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Why can I not switch branches?

Since the file is modified by both, Either you need to add it by

git add Whereami.xcodeproj/project.xcworkspace/xcuserdatauser.xcuserdatad/UserInterfaceState.xcuserstate

Or if you would like to ignore yoyr changes, then do

git reset HEAD Whereami.xcodeproj/project.xcworkspace/xcuserdatauser.xcuserdatad/UserInterfaceState.xcuserstate

After that just switch your branch.This should do the trick.

How to display a database table on to the table in the JSP page

you can also print the data onto your HTML/JSP document. like:-

<!DOCTYPE html>
<html>
<head>
    <title>Jsp Sample</title>
    <%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
    <%
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection)DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/forum","root","root");
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from student;");
    %><table border=1 align=center style="text-align:center">
      <thead>
          <tr>
             <th>ID</th>
             <th>NAME</th>
             <th>SKILL</th>
             <th>ACTION</th>
          </tr>
      </thead>
      <tbody>
        <%while(rs.next())
        {
            %>
            <tr>
                <td><%=rs.getString("id") %></td>
                <td><%=rs.getString("name") %></td>
                <td><%=rs.getString("skill") %></td>
                <td><%=rs.getString("action") %></td>
            </tr>
            <%}%>
           </tbody>
        </table><br>
    <%}
    catch(Exception e){
        out.print(e.getMessage());%><br><%
    }
    finally{
        st.close();
        con.close();
    }
    %>
</body>
</html>

<!--executeUpdate() mainupulation and executeQuery() for retriving-->

How can I capitalize the first letter of each word in a string?

The .title() method won't work in all test cases, so using .capitalize(), .replace() and .split() together is the best choice to capitalize the first letter of each word.

eg: def caps(y):

     k=y.split()
     for i in k:
        y=y.replace(i,i.capitalize())
     return y

Installing Node.js (and npm) on Windows 10

I had the same problem, what helped we was turning of my anti virus protection for like 10 minutes while node installed and it worked like a charm.

Set selected radio from radio group with a value

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

How to convert a Hibernate proxy to a real entity object

Thank you for the suggested solutions! Unfortunately, none of them worked for my case: receiving a list of CLOB objects from Oracle database through JPA - Hibernate, using a native query.

All of the proposed approaches gave me either a ClassCastException or just returned java Proxy object (which deeply inside contained the desired Clob).

So my solution is the following (based on several above approaches):

Query sqlQuery = manager.createNativeQuery(queryStr);
List resultList = sqlQuery.getResultList();
for ( Object resultProxy : resultList ) {
    String unproxiedClob = unproxyClob(resultProxy);
    if ( unproxiedClob != null ) {
       resultCollection.add(unproxiedClob);
    }
}

private String unproxyClob(Object proxy) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            Method readMethod = property.getReadMethod();
            if ( readMethod.getName().contains("getWrappedClob") ) {
                Object result = readMethod.invoke(proxy);
                return clobToString((Clob) result);
            }
        }
    }
    catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException e) {
        LOG.error("Unable to unproxy CLOB value.", e);
    }
    return null;
}

private String clobToString(Clob data) throws SQLException, IOException {
    StringBuilder sb = new StringBuilder();
    Reader reader = data.getCharacterStream();
    BufferedReader br = new BufferedReader(reader);

    String line;
    while( null != (line = br.readLine()) ) {
        sb.append(line);
    }
    br.close();

    return sb.toString();
}

Hope this will help somebody!

jQuery: How to get to a particular child of a parent?

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

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

You can archive a remote repo at any commit as zip file.

git archive --format=zip --output=archive.zip --remote=USERNAME@HOSTNAME:PROJECTNAME.git HASHOFGITCOMMIT

show loading icon until the page is load?

Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.

<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
    jQuery("#" + id).html(jQuery("#loading").html());
    jQuery("#" + id).show();
}

Maven: best way of linking custom external JAR to my project?

If you meet the same problem and you are using spring-boot v1.4+, you can do it in this way.

There is an includeSystemScope that you can use to add system-scope dependencies to the jar.

e.g.

I'm using oracle driver into my project.

<dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>10.2.0.3.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/src/main/resources/extra-jars/ojdbc14-10.2.0.3.0.jar</systemPath>
    </dependency>

then make includeSystemScope=true to include the jar into path /BOOT-INF/lib/**

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

and exclude from resource to avoid duplicated include, the jar is fat enought~

<build>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>**/*.jar</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Good luck!

Align two inline-blocks left and right on same line

Taking advantage of @skip405's answer, I've made a Sass mixin for it:

@mixin inline-block-lr($container,$left,$right){
    #{$container}{        
        text-align: justify; 

        &:after{
            content: '';
            display: inline-block;
            width: 100%;
            height: 0;
            font-size:0;
            line-height:0;
        }
    }

    #{$left} {
        display: inline-block;
        vertical-align: middle; 
    }

    #{$right} {
        display: inline-block;
        vertical-align: middle; 
    }
}

It accepts 3 parameters. The container, the left and the right element. For example, to fit the question, you could use it like this:

@include inline-block-lr('header', 'h1', 'nav');

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

If you are using Auto mapper and facing the the issue following is the good solution, it work for me

https://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplusfailed

Since the problem is that we're mapping null navigation properties, and we actually don't need them to be updated on the Entity since they didn't changed on the Contract, we need to ignore them on the mapping definition:

ForMember(dest => dest.RefundType, opt => opt.Ignore())

So my code ended up like this:

Mapper.CreateMap<MyDataContract, MyEntity>
ForMember(dest => dest.NavigationProperty1, opt => opt.Ignore())
ForMember(dest => dest.NavigationProperty2, opt => opt.Ignore())
.IgnoreAllNonExisting();

How to use Switch in SQL Server

Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:

IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)

Start HTML5 video at a particular position when loading?

WITHOUT USING JAVASCRIPT

Just add #t=[(start_time), (end_time)] to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time. Example:

<video>
    <source src="splash.mp4#t=10,20" type="video/mp4">
</video>

Notes: Not supported in IE

Javascript variable access in HTML

It is also possible to use span tag instead of a tag:

<html>
<script>
   var simpleText = "hello_world";
   var finalSplitText = simpleText.split("_");
   var splitText = finalSplitText[0];

   document.getElementById('someId').InnerHTML = splitText;
</script>

 <body>
  <span id="someId"></span>
 </body>

</html>

It worked well for me

How do I create a sequence in MySQL?

Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

Without additional details on the specific error, it is difficult to provide more specific help.

UPDATE

CREATE TABLE ORD (
  ORDID INT NOT NULL AUTO_INCREMENT,
  //Rest of table code
  PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;

This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

ALTER TABLE ORD AUTO_INCREMENT = 622;

UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.

How to insert data to MySQL having auto incremented primary key?

The default keyword works for me:

mysql> insert into user_table (user_id, ip, partial_ip, source, user_edit_date, username) values 
(default, '39.48.49.126', null, 'user signup page', now(), 'newUser');
---
Query OK, 1 row affected (0.00 sec)

I'm running mysql --version 5.1.66:

mysql  Ver 14.14 Distrib **5.1.66**, for debian-linux-gnu (x86_64) using readline 6.1

How to Generate unique file names in C#

If readability doesn't matter, use GUIDs.

E.g.:

var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());

or shorter:

var myUniqueFileName = $@"{Guid.NewGuid()}.txt";

In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png"…"Image10.png") and if that fails (because the file already exists), I fall back to GUIDs.

Update:

Recently, I've also use DateTime.Now.Ticks instead of GUIDs:

var myUniqueFileName = string.Format(@"{0}.txt", DateTime.Now.Ticks);

or

var myUniqueFileName = $@"{DateTime.Now.Ticks}.txt";

The benefit to me is that this generates a shorter and "nicer looking" filename, compared to GUIDs.

Please note that in some cases (e.g. when generating a lot of random names in a very short time), this might make non-unique values.

Stick to GUIDs if you want to make really sure that the file names are unique, even when transfering them to other computers.

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

How to generate a random int in C?

Lets go through this. First we use the srand() function to seed the randomizer. Basically, the computer can generate random numbers based on the number that is fed to srand(). If you gave the same seed value, then the same random numbers would be generated every time.

Therefore, we have to seed the randomizer with a value that is always changing. We do this by feeding it the value of the current time with the time() function.

Now, when we call rand(), a new random number will be produced every time.

    #include <stdio.h>

    int random_number(int min_num, int max_num);

    int main(void)
    {
        printf("Min : 1 Max : 40 %d\n", random_number(1,40));
        printf("Min : 100 Max : 1000 %d\n",random_number(100,1000));
        return 0;
    }

    int random_number(int min_num, int max_num)
    {
        int result = 0, low_num = 0, hi_num = 0;

        if (min_num < max_num)
        {
            low_num = min_num;
            hi_num = max_num + 1; // include max_num in output
        } else {
            low_num = max_num + 1; // include max_num in output
            hi_num = min_num;
        }

        srand(time(NULL));
        result = (rand() % (hi_num - low_num)) + low_num;
        return result;
    }

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

How to get Toolbar from fragment?

Maybe you have to try getActivity().getSupportActionBar().setTitle() if you are using support_v7.

Split string into array of characters?

Safest & simplest is to just loop;

Dim buff() As String
ReDim buff(Len(my_string) - 1)
For i = 1 To Len(my_string)
    buff(i - 1) = Mid$(my_string, i, 1)
Next

If your guaranteed to use ansi characters only you can;

Dim buff() As String
buff = Split(StrConv(my_string, vbUnicode), Chr$(0))
ReDim Preserve buff(UBound(buff) - 1)

How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Source

Remove empty space before cells in UITableView

You can use this code into viewDidLoad or viewDidAppear where your table being created:

// Remove blank space on header of table view
 videoListUITableView.contentInset = UIEdgeInsetsZero;

// The iOS device = iPhone or iPod Touch
CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;

// Set the height of the table on the basis of number of rows
videoListUITableView.frame = CGRectMake(videoListUITableView.frame.origin.x, videoListUITableView.frame.origin.y, videoListUITableView.frame.size.width, iOSDeviceScreenSize.height-100);



// Hide those cell which doesn't contain any kind of data
self.videoListUITableView.tableFooterView = [[UIView alloc] init];

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

The two methods are 100% equivalent.

I’m not sure why Microsoft felt the need to include this extra Clear method but since it’s there, I recommend using it, as it clearly expresses its purpose.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

If you can run the website in Visual Studio debugger, then might be able to see where in your code the application pool is crashing. In my case, it was a function being called recursively an unlimited number of times, and that caused a stack overflow. Note: the Windows event log and the IIS logs were not helpful to diagnose the problem.

How to check whether an object has certain method/property?

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

How can I convert a dictionary into a list of tuples?

A simpler one would be

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

Best way to incorporate Volley (or other library) into Android Studio project

LATEST UPDATE:

Use the official version from jCenter instead.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

The dependencies below points to deprecated volley that is no longer maintained.

ORIGINAL ANSWER

You can use this in dependency section of your build.gradle file to use volley

  dependencies {
      compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  }

UPDATED:

Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.

https://github.com/mcxiaoke/android-volley

What does "Could not find or load main class" mean?

Answering with respect to an external library -

Compile:

javac -cp ./<external lib jar>: <program-name>.java

Execute:

java -cp ./<external lib jar>: <program-name>

The above scheme works well in OS X and Linux systems. Notice the : in the classpath.

Pandas count(distinct) equivalent

I believe this is what you want:

table.groupby('YEARMONTH').CLIENTCODE.nunique()

Example:

In [2]: table
Out[2]: 
   CLIENTCODE  YEARMONTH
0           1     201301
1           1     201301
2           2     201301
3           1     201302
4           2     201302
5           2     201302
6           3     201302

In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]: 
YEARMONTH
201301       2
201302       3

Convert string into Date type on Python

You can do that with datetime.strptime()

Example:

>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5

You can find the table with all the strptime directive here.


To increment by 2 days if .isweekday() == 6, you can use timedelta():

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
...     date += datetime.timedelta(days=2)
... 
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d')   # if you want a string again
'2012-02-13'

How to implement linear interpolation?

As I understand your question, you want to write some function y = interpolate(x_values, y_values, x), which will give you the y value at some x? The basic idea then follows these steps:

  1. Find the indices of the values in x_values which define an interval containing x. For instance, for x=3 with your example lists, the containing interval would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2
  2. Calculate the slope on this interval by (y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1]) (ie dy/dx).
  3. The value at x is now the value at x1 plus the slope multiplied by the distance from x1.

You will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.

Did this help, or did you need more specific advice?

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

How to check if cursor exists (open status)

I rarely employ cursors, but I just discovered one other item that can bite you here, the scope of the cursor name.

If the database CURSOR_DEFAULT is global, you will get the "cursor already exists" error if you declare a cursor in a stored procedure with a particular name (eg "cur"), and while that cursor is open you call another stored procedure which declares and opens a cursor with the same name (eg "cur"). The error will occur in the nested stored procedure when it attempts to open "cur".

Run this bit of sql to see your CURSOR_DEFAULT:

select is_local_cursor_default from sys.databases where name = '[your database name]'

If this value is "0" then how you name your nested cursor matters!

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

How to label scatterplot points by name?

None of these worked for me. I'm on a mac using Microsoft 360. I found this which DID work: This workaround is for Excel 2010 and 2007, it is best for a small number of chart data points.

Click twice on a label to select it. Click in formula bar. Type = Use your mouse to click on a cell that contains the value you want to use. The formula bar changes to perhaps =Sheet1!$D$3

Repeat step 1 to 5 with remaining data labels.

Simple

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

/bin/sh: pushd: not found

Synthesizing from the other responses: pushd is bash-specific and you are make is using another POSIX shell. There is a simple workaround to use separate shell for the part that needs different directory, so just try changing it to:

test -z gen || mkdir -p gen \
 && ( cd $(CURRENT_DIRECTORY)/genscript > /dev/null \
 && perl genmakefile.pl \
 && mv Makefile ../gen/ ) \
 && echo "" > $(CURRENT_DIRECTORY)/gen/SvcGenLog

(I substituted the long path with a variable expansion. I probably is one in the makefile and it clearly expands to the current directory).

Since you are running it from make, I would probably replace the test with a make rule, too. Just

gen/SvcGenLog :
    mkdir -p gen
    cd genscript > /dev/null \
     && perl genmakefile.pl \
     && mv Makefile ../gen/ \
    echo "" > gen/SvcGenLog

(dropped the current directory prefix; you were using relative path at some points anyway) And than just make the rule depend on gen/SvcGenLog. It would be a bit more readable and you can make it depend on the genscript/genmakefile.pl too, so the Makefile in gen will be regenerated if you modify the script. Of course if anything else affects the content of the Makefile, you can make the rule depend on that too.

Using :focus to style outer div?

Simple use JQuery.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("div .FormRow").focusin(function() {_x000D_
    $(this).css("background-color", "#FFFFCC");_x000D_
    $(this).css("border", "3px solid #555");_x000D_
  });_x000D_
  $("div .FormRow").focusout(function() {_x000D_
    $(this).css("background-color", "#FFFFFF");_x000D_
    $(this).css("border", "0px solid #555");_x000D_
  });_x000D_
});
_x000D_
    .FormRow {_x000D_
      padding: 10px;_x000D_
    }
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div style="border: 0px solid black;padding:10px;">_x000D_
    <div class="FormRow">_x000D_
      First Name:_x000D_
      <input type="text">_x000D_
      <br>_x000D_
    </div>_x000D_
    <div class="FormRow">_x000D_
      Last Name:_x000D_
      <input type="text">_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <ul>_x000D_
    <li><strong><em>Click an input field to get focus.</em></strong>_x000D_
    </li>_x000D_
    <li><strong><em>Click outside an input field to lose focus.</em></strong>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Why isn't my Pandas 'apply' function referencing multiple columns working?

This is same as the previous solution but I have defined the function in df.apply itself:

df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)

How do you remove Subversion control for a folder?

From a Windows command line:

rmdir .svn /s /q

HTML display result in text (input) field?

 <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>

      </BODY>
</HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

What are these attributes: `aria-labelledby` and `aria-hidden`

The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div has role="dialog". When the screen reader notices that a div becomes visible which has this role, it'll speak the label for that div.

There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label> HTML tag. With HTML modals the label is usually a <h> header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader], and the screen reader will speak that header when the modal appears.

Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden property is frequently redundant and can probably be skipped in most cases.

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

Padding is invalid and cannot be removed?

I had the same error. In my case it was because I have stored the encrypted data in a SQL Database. The table the data is stored in, has a binary(1000) data type. When retreiving the data from the database, it would decrypt these 1000 bytes, while there where actually 400 bytes. So removing the trailing zero's (600) from the result it fixed the problem.

Python dictionary: are keys() and values() always the same order?

I wasn't satisfied with these answers since I wanted to ensure the exported values had the same ordering even when using different dicts.

Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

keys = dict1.keys()
ordered_keys1 = [dict1[cur_key] for cur_key in keys]
ordered_keys2 = [dict2[cur_key] for cur_key in keys]

How to return first 5 objects of Array in Swift?

Update for swift 4:

[0,1,2,3,4,5].enumerated().compactMap{ $0 < 10000 ? $1 : nil }

For swift 3:

[0,1,2,3,4,5].enumerated().flatMap{ $0 < 10000 ? $1 : nil }

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Adding div element to body or document in JavaScript

Try this out:-

http://jsfiddle.net/adiioo7/vmfbA/

Use

document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

instead of

document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

Edit:- Ideally you should use body.appendChild method instead of changing the innerHTML

var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);

How to insert logo with the title of a HTML page?

Put this in the <head> section:

<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />

Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.

Count lines in large files

On a multi-core server, use GNU parallel to count file lines in parallel. After each files line count is printed, bc sums all line counts.

find . -name '*.txt' | parallel 'wc -l {}' 2>/dev/null | paste -sd+ - | bc

To save space, you can even keep all files compressed. The following line uncompresses each file and counts its lines in parallel, then sums all counts.

find . -name '*.xz' | parallel 'xzcat {} | wc -l' 2>/dev/null | paste -sd+ - | bc

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

If you are using the following stack: Server Version: Apache Tomcat/9.0.21 Servlet Version: 4.0 JSP Version: 2.3

Then try adding <absolute-ordering /> to your web.xml file. So your file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <absolute-ordering />

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  ......

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

iOS Simulator to test website on Mac

You could also download Xcode to your mac and use iPhone simulator.

Reporting Services export to Excel with Multiple Worksheets

As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here

Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.

How to create a String with carriage returns?

Do this: Step 1: Your String

String str = ";;;;;;\n" +
            "Name, number, address;;;;;;\n" + 
             "01.01.12-16.02.12;;;;;;\n" + 
             ";;;;;;\n" + 
             ";;;;;;";

Step 2: Just replace all "\n" with "%n" the result looks like this

String str = ";;;;;;%n" +
             "Name, number, address;;;;;;%n" + 
             "01.01.12-16.02.12;;;;;;%n" + 
            ";;;;;;%n" + 
            ";;;;;;";

Notice I've just put "%n" in place of "\n"

Step 3: Now simply call format()

str=String.format(str);

That's all you have to do.

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

How to compare two files in Notepad++ v6.6.8

2018 10 25. Update.

Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.

Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.

Function in JavaScript that can be called only once

try this

var fun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I  called");
      called = true;
    }
  }
})()

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

Creating instance list of different objects

List anyObject = new ArrayList();

or

List<Object> anyObject = new ArrayList<Object>();

now anyObject can hold objects of any type.

use instanceof to know what kind of object it is.

How to get the first and last date of the current year?

If it reaches the 1st of Jan you might it to be still last years date.

select
convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AS StartOfYear,
convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 )AS EndOfYear

C# - Winforms - Global Variables

If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.

//Program.cs
public class Forms : Form
{
    //Declare your global valuables here.
}

//Form1.cs
public partial class Form1 : Forms    //Change from Form to Forms
{
    //...
}

Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!

How to create radio buttons and checkbox in swift (iOS)?

  1. Create 2 buttons one as "YES" and another as "NO".
  2. Create a BOOL property Ex: isNRICitizen = false
  3. Give same button connection to both the buttons and set a tag (Ex: Yes button - tag 10 and No button -tag 20)
@IBAction func btnAction(_ sender:UIButton) {

isNRICitizen = sender.tag == 10 ? true : false
isNRICitizen ? self.nriCitizenBtnYes.setImage(#imageLiteral(resourceName: "radioChecked"), for: .normal) : self.nriCitizenBtnYes.setImage(#imageLiteral(resourceName: "radioUnchecked"), for: .normal)
        isNRICitizen ? self.nriCitizenBtnNo.setImage(#imageLiteral(resourceName: "radioUnchecked"), for: .normal) : self.nriCitizenBtnNo.setImage(#imageLiteral(resourceName: "radioChecked"), for: .normal)
}

How to specify an element after which to wrap in css flexbox?

The only thing that appears to work is to set flex-wrap: wrap; on the container and them somehow make the child you want to break out after to fill the full width, so width: 100%; should work.

If, however, you can't stretch the element to 100% (for example, if it's an <img>), you can apply a margin to it, like width: 50px; margin-right: calc(100% - 50px).

Enable binary mode while restoring a Database from an SQL dump

zcat /path/to/file.sql.gz | mysql -u 'root' -p your_database

Rails Model find where not equal

In Rails 3, I don't know anything fancier. However, I'm not sure if you're aware, your not equal condition does not match for (user_id) NULL values. If you want that, you'll have to do something like this:

GroupUser.where("user_id != ? OR user_id IS NULL", me)

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

To get past INSTALL_FAILED_MISSING_SHARED_LIBRARY error with Google Maps for Android:

  1. Install Google map APIs. This can be done in Eclipse Windows/Android SDK and AVD Manager -> Available Packages -> Third Party Add-ons -> Google Inc. -> Google APIs by Google Inc., Android API X

  2. From command line create new AVD. This can be done by listing targets (android list targets), then android create avd -n new_avd_api_233 -t "Google Inc.:Google APIs:X"

  3. Then create AVD (Android Virtual Device) in Eclipse Windows/Android SDK and AVD Manager -> New... -> (Name: new_avd_X, Target: Google APIs (Google Inc.) - API Level X)

    IMPORTANT : You must create your AVD with Target as Google APIs (Google Inc.) otherwise it will again failed.

  4. Create Android Project in Eclipse File/New/Android Project and select Google APIs Build Target.

  5. add <uses-library android:name="com.google.android.maps" /> between <application> </application> tags.

  6. Run Project as Android Application.

If error persists, then you still have problems, if it works, then this error is forever behind you.

How to set tint for an image view programmatically in android?

Adding to ADev's answer (which in my opinion is the most correct), since the widespread adoption of Kotlin, and its useful extension functions:

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

I think this is a function which could be useful to have in any Android project!

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

how to remove pagination in datatable

DISABLE PAGINATION

For DataTables 1.9

Use bPaginate option to disable pagination.

$('#example').dataTable({
    "bPaginate": false
});

For DataTables 1.10+

Use paging option to disable pagination.

$('#example').dataTable({
    "paging": false
});

See this jsFiddle for code and demonstration.

REMOVE PAGINATION CONTROL AND LEAVE PAGINATION ENABLED

For DataTables 1.9

Use sDom option to configure which control elements appear on the page.

$('#example').dataTable({
    "sDom": "lfrti"
});

For DataTables 1.10+

Use dom option to configure which control elements appear on the page.

$('#example').dataTable({
    "dom": "lfrti"
});

See this jsFiddle for code and demonstration.

How to disable HTML links

You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).

CSS way

This should be the right way (but see later) to do it when most of browsers will support it:

a.disabled {
    pointer-events: none;
}

It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:

span.disable-links {
    pointer-events: none;
}

With:

<span class="disable-links"><a href="#">...</a></span>

Workaround

We, probably, need to define a CSS class for pointer-events: none but what if we reuse the disabled attribute instead of a CSS class? Strictly speaking disabled is not supported for <a> but browsers won't complain for unknown attributes. Using the disabled attribute IE will ignore pointer-events but it will honor IE specific disabled attribute; other CSS compliant browsers will ignore unknown disabled attribute and honor pointer-events. Easier to write than to explain:

a[disabled] {
    pointer-events: none;
}

Another option for IE 11 is to set display of link elements to block or inline-block:

<a style="pointer-events: none; display: inline-block;" href="#">...</a>

Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...

All this said please note that pointer-events disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.

Focus

In conjunction with above described CSS technique you may use tabindex in a non-standard way to prevent an element to be focused:

<a href="#" disabled tabindex="-1">...</a>

I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex cannot be changed from CSS.

Intercept clicks

Use a href to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.

$("td > a").on("click", function(event){
    if ($(this).is("[disabled]")) {
        event.preventDefault();
    }
});

To disable links do this:

$("td > a").attr("disabled", "disabled");

To re-enable them:

$("td > a").removeAttr("disabled");

If you want instead of .is("[disabled]") you may use .attr("disabled") != undefined (jQuery 1.6+ will always return undefined when the attribute is not set) but is() is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]") with .hasClass("disabled") (adding and removing with addClass() and removeClass()).

Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart, mousedown and keydown events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.

Note that if href isn't cleared it's possible for the user to manually visit that page.

Clear the link

Clear the href attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:

$("td > a").each(function() {
    this.data("href", this.attr("href"))
        .attr("href", "javascript:void(0)")
        .attr("disabled", "disabled");
});

And this one to re-enable them:

$("td > a").each(function() {
    this.attr("href", this.data("href")).removeAttr("disabled");
});

Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.

Fake click handler

Add/remove an onclick function where you return false, link won't be followed. To disable links:

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

To re-enable them:

$("td > a").removeAttr("disabled").off("click");

I do not think there is a reason to prefer this solution instead of the first one.

Styling

Styling is even more simple, whatever solution you're using to disable the link we did add a disabled attribute so you can use following CSS rule:

a[disabled] {
    color: gray;
}

If you're using a class instead of attribute:

a.disabled {
    color: gray;
}

If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled attribute and with .disabled class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a> without href is still painted as enabled.

Accessible Rich Internet Applications (ARIA)

Do not forget to also include an attribute aria-disabled="true" together with disabled attribute/class.

Unrecognized SSL message, plaintext connection? Exception

I got the same error message when I forgot to log in to the company firewall, before performing a POST request through a proxy.

What does `ValueError: cannot reindex from a duplicate axis` mean?

Simple Fix that Worked for Me

Run df.reset_index(inplace=True) before grouping.

Thank you to this github comment for the solution.

Remove inplace if you want it to return the dataframe.

How to set width of mat-table column in angular?

You can do it by using below CSS:

table {
  width: 100%;
  table-layout: fixed;
}

th, td {
  overflow: hidden;
  width: 200px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Here is a StackBlitz Example with Sample Data

How to center a navigation bar with CSS or HTML?

You could also use float and inline-block to center your nav like the following:

nav li {
   float: left;
}
nav {
   display: inline-block;
}

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

Add Bean Programmatically to Spring Web App Context

Actually AnnotationConfigApplicationContext derived from AbstractApplicationContext, which has empty postProcessBeanFactory method left for override

/**
 * Modify the application context's internal bean factory after its standard
 * initialization. All bean definitions will have been loaded, but no beans
 * will have been instantiated yet. This allows for registering special
 * BeanPostProcessors etc in certain ApplicationContext implementations.
 * @param beanFactory the bean factory used by the application context
 */
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

To leverage this, Create AnnotationConfigApplicationContextProvider class which may look like following(given for Vertx instance example, you can use MyClass instead)...

public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;

public CustomAnnotationApplicationContextProvider(Vertx vertx) {
    this.vertx = vertx;
}

/**
 * Register all beans to spring bean factory
 *
 * @param beanFactory, spring bean factory to register your instances
 */
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.registerSingleton("vertx", vertx);
}

/**
 * Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
 *
 * @return {@link AnnotationConfigApplicationContext} instance
 */
public AnnotationConfigApplicationContext get() {
    return new AnnotationConfigApplicationContext() {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
 *
 * @param beanFactory bean factory for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
 */
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
    return new AnnotationConfigApplicationContext(beanFactory) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
 *
 * @param annotatedClasses, set of annotated classes for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
 */
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
    return new AnnotationConfigApplicationContext(annotatedClasses) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
 *
 * @param basePackages set of base packages for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
 */
public AnnotationConfigApplicationContext get(String... basePackages) {
    return new AnnotationConfigApplicationContext(basePackages) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}
}

While creating ApplicationContext you can create it using

Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

This worked for me for a format like YYYY.MM.DD-HH.MM.SS.fff. Attempting to make this code capable of accepting any string format will be like reinventing the wheel (i.e. there are functions for all this in Boost.

std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
    using namespace std;
    using namespace std::chrono;

    int yyyy, mm, dd, HH, MM, SS, fff;

    char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";

    sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);

    tm ttm = tm();
    ttm.tm_year = yyyy - 1900; // Year since 1900
    ttm.tm_mon = mm - 1; // Month since January 
    ttm.tm_mday = dd; // Day of the month [1-31]
    ttm.tm_hour = HH; // Hour of the day [00-23]
    ttm.tm_min = MM;
    ttm.tm_sec = SS;

    time_t ttime_t = mktime(&ttm);

    system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);

    time_point_result += std::chrono::milliseconds(fff);
    return time_point_result;
}

std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
    using namespace std;
    using namespace std::chrono;

    auto ttime_t = system_clock::to_time_t(tp);
    auto tp_sec = system_clock::from_time_t(ttime_t);
    milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);

    std::tm * ttm = localtime(&ttime_t);

    char date_time_format[] = "%Y.%m.%d-%H.%M.%S";

    char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";

    strftime(time_str, strlen(time_str), date_time_format, ttm);

    string result(time_str);
    result.append(".");
    result.append(to_string(ms.count()));

    return result;
}

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

UICollectionView current visible cell index

For Swift 3.0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: colView.contentOffset, size: colView.bounds.size)
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let indexPath = colView.indexPathForItem(at: visiblePoint)
}

JavaScript + Unicode regexes

Situation for ES 6

The upcoming ECMAScript language specification, edition 6, includes Unicode-aware regular expressions. Support must be enabled with the u modifier on the regex. See Unicode-aware regular expressions in ES6.

Until ES 6 is finished and widely adopted among browser vendors you're still on your own, though. Update: There is now a transpiler named regexpu that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. Try it out online.

Situation for ES 5 and below

Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.

Referencing value in a closed Excel workbook using INDIRECT?

This seems to work with closed file: add a pivot table (rows, tabular layout, no subtotals, no grand totals) of the source to the current workbook, then reference all you want from that pivot table, INDIRECT, LOOKUPs,...

How do I remove duplicate items from an array in Perl?

Install List::MoreUtils from CPAN

Then in your code:

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @dup_list = qw(1 1 1 2 3 4 4);

my @uniq_list = uniq(@dup_list);

Disable button in WPF?

I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.

Xaml:

<StackPanel Orientation="Horizontal">
   <TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
   <Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>

CodeBehind:

Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Button01.IsEnabled = False
        Button01.Content = "I am Disabled"

End Sub

Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged

        If TextBox01.Text.Trim.Length > 0 Then
            Button01.IsEnabled = True
            Button01.Content = "I am Enabled"
        Else
            Button01.IsEnabled = False
            Button01.Content = "I am Disabled"
        End If

End Sub

Connection pooling options with JDBC: DBCP vs C3P0

Have been using DBCP for a couple of years now in production. It is stable, survives DB server reboot. Just configure it properly. It only requires a handful of parameters to be specified so don't be lazy. Here is a snippet from our system production code which lists parameters that we explicitly set to make it work:

DriverAdapterCPDS driverAdapterCPDS = new DriverAdapterCPDS();
driverAdapterCPDS.setUrl(dataSourceProperties.getProperty("url"));
driverAdapterCPDS.setUser(dataSourceProperties.getProperty("username"));
driverAdapterCPDS.setPassword(dataSourceProperties.getProperty("password"));
driverAdapterCPDS.setDriver(dataSourceProperties.getProperty("driverClass"));

driverAdapterCPDS.setMaxActive(Integer.valueOf(dataSourceProperties.getProperty("maxActive")));
driverAdapterCPDS.setMaxIdle(Integer.valueOf(dataSourceProperties.getProperty("maxIdle")));
driverAdapterCPDS.setPoolPreparedStatements(Boolean.valueOf(dataSourceProperties.getProperty("poolPreparedStatements")));

SharedPoolDataSource poolDataSource = new SharedPoolDataSource();
poolDataSource.setConnectionPoolDataSource(driverAdapterCPDS);
poolDataSource.setMaxWait(Integer.valueOf(dataSourceProperties.getProperty("maxWait")));
poolDataSource.setDefaultTransactionIsolation(Integer.valueOf(dataSourceProperties.getProperty("defaultTransactionIsolation")));
poolDataSource.setDefaultReadOnly(Boolean.valueOf(dataSourceProperties.getProperty("defaultReadOnly")));
poolDataSource.setTestOnBorrow(Boolean.valueOf(dataSourceProperties.getProperty("testOnBorrow")));
poolDataSource.setValidationQuery("SELECT 0");

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How can I get the concatenation of two lists in Python without modifying either one?

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

HashMap - getting First Key value

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

Why can't decimal numbers be represented exactly in binary?

BCD - Binary-coded Decimal - representations are exact. They are not very space-efficient, but that's a trade-off you have to make for accuracy in this case.

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Generate a heatmap in MatPlotLib using a scatter data set

enter image description here

Here's one I made on a 1 Million point set with 3 categories (colored Red, Green, and Blue). Here's a link to the repository if you'd like to try the function. Github Repo

histplot(
    X,
    Y,
    labels,
    bins=2000,
    range=((-3,3),(-3,3)),
    normalize_each_label=True,
    colors = [
        [1,0,0],
        [0,1,0],
        [0,0,1]],
    gain=50)

How to set a Javascript object values dynamically?

simple as this myObj.name = value;

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

Find out which remote branch a local branch is tracking

I don't know if this counts as parsing the output of git config, but this will determine the URL of the remote that master is tracking:

$ git config remote.$(git config branch.master.remote).url

Right HTTP status code to wrong input

We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an InvalidArgumentException. After reading the source article below, we ended up using 422 Unprocessable Entity which states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

source: https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

Using a dictionary to select function to execute

Simplify, simplify, simplify + DRY:

tasks = {}
task = lambda f: tasks.setdefault(f.__name__, f)

@task
def p1():
    whatever

@task
def p2():
    whatever

def my_main(key):
    tasks[key]()

What is setContentView(R.layout.main)?

You can set content view (or design) of an activity. For example you can do it like this too :

public void onCreate(Bundle savedinstanceState) {
    super.onCreate(savedinstanceState);

    Button testButon = new Button(this);

    setContentView(testButon);   
}

Also watch this tutorial too.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

On Android 8:

apache.commons.io:2.4

gives INSTALL_FAILED_NO_MATCHING_ABIS, try to change it to implementation 'commons-io:commons-io:2.6' and it will worK.

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview

Replace a string in a file with nodejs

Since replace wasn't working for me, I've created a simple npm package replace-in-file to quickly replace text in one or more files. It's partially based on @asgoth's answer.

Edit (3 October 2016): The package now supports promises and globs, and the usage instructions have been updated to reflect this.

Edit (16 March 2018): The package has amassed over 100k monthly downloads now and has been extended with additional features as well as a CLI tool.

Install:

npm install replace-in-file

Require module

const replace = require('replace-in-file');

Specify replacement options

const options = {

  //Single file
  files: 'path/to/file',

  //Multiple files
  files: [
    'path/to/file',
    'path/to/other/file',
  ],

  //Glob(s) 
  files: [
    'path/to/files/*.html',
    'another/**/*.path',
  ],

  //Replacement to make (string or regex) 
  from: /Find me/g,
  to: 'Replacement',
};

Asynchronous replacement with promises:

replace(options)
  .then(changedFiles => {
    console.log('Modified files:', changedFiles.join(', '));
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Asynchronous replacement with callback:

replace(options, (error, changedFiles) => {
  if (error) {
    return console.error('Error occurred:', error);
  }
  console.log('Modified files:', changedFiles.join(', '));
});

Synchronous replacement:

try {
  let changedFiles = replace.sync(options);
  console.log('Modified files:', changedFiles.join(', '));
}
catch (error) {
  console.error('Error occurred:', error);
}

Reading a string with spaces with sscanf

I guess this is what you want, it does exactly what you specified.

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

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d cool %s", &age, buffer);
    printf("cool %s is %d years old\n", buffer, age);
    return 0;
}

The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.

Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".

jquery AJAX and json format

I never had any luck with that approach. I always do this (hope this helps):

var obj = {};

obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();

Then in your ajax:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

What's the difference between Thread start() and Runnable run()

The difference is that when program calls start() method, a new thread is created and code inside run() is executed in the new thread: while if you call run() method directly, no new thread will be created and code inside run() will execute in the current thread directly.

Another difference between start() and run() in Java thread is that you cannot call start() twice. Once started, second start() call will throw IllegalStateException in Java while you can call run() method several times since it's just an ordinary method.

Adding text to ImageView in Android

I know this question has been and gone, but if anyone else stumbled across this I wanted to let them know. This may sound an unintuitive thing to do but you could use a button with clickable set to false or what ever. This is because a button allows one to set drawableLeft, drawableRight, drawableTop etc in addition to text.

  <Button
  android:id="@+id/button1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/border_box1"
  android:drawableLeft="@drawable/ar9_but_desc"
  android:padding="20dp"
  android:text="@string/ar4_button1"
  android:textColor="@color/white"
  android:textSize="24sp" />

New Info: A button can have icons in drawableLeft, drawableRight, drawableTop, and drawableBottom. This makes a standard button much more flexible than an image button. The left, right, top etc is the relation to the text in the button. You can have multiple drawables on the button for example one left, one right and the text in the middle.

How do I get the current mouse screen coordinates in WPF?

To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.

1.Using Windows Forms. Add a reference to System.Windows.Forms

public static Point GetMousePositionWindowsForms()
{
    var point = Control.MousePosition;
    return new Point(point.X, point.Y);
}

2.Using Win32

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);

[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
    public Int32 X;
    public Int32 Y;
};
public static Point GetMousePosition()
{
    var w32Mouse = new Win32Point();
    GetCursorPos(ref w32Mouse);

    return new Point(w32Mouse.X, w32Mouse.Y);
}

Searching for file in directories recursively

you can do something like this:

foreach (var file in Directory.GetFiles(MyFolder, "*.xml", SearchOption.AllDirectories))
        {
            // do something with this file
        }

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

You may also consider stratified division into training and testing set. Startified division also generates training and testing set randomly but in such a way that original class proportions are preserved. This makes training and testing sets better reflect the properties of the original dataset.

import numpy as np  

def get_train_test_inds(y,train_proportion=0.7):
    '''Generates indices, making random stratified split into training set and testing sets
    with proportions train_proportion and (1-train_proportion) of initial sample.
    y is any iterable indicating classes of each observation in the sample.
    Initial proportions of classes inside training and 
    testing sets are preserved (stratified sampling).
    '''

    y=np.array(y)
    train_inds = np.zeros(len(y),dtype=bool)
    test_inds = np.zeros(len(y),dtype=bool)
    values = np.unique(y)
    for value in values:
        value_inds = np.nonzero(y==value)[0]
        np.random.shuffle(value_inds)
        n = int(train_proportion*len(value_inds))

        train_inds[value_inds[:n]]=True
        test_inds[value_inds[n:]]=True

    return train_inds,test_inds

y = np.array([1,1,2,2,3,3])
train_inds,test_inds = get_train_test_inds(y,train_proportion=0.5)
print y[train_inds]
print y[test_inds]

This code outputs:

[1 2 3]
[1 2 3]

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

How do I post form data with fetch api?

With fetch api it turned out that you do NOT have to include headers "Content-type": "multipart/form-data".

So the following works:

let formData = new FormData()
formData.append("nameField", fileToSend)

fetch(yourUrlToPost, {
   method: "POST",
   body: formData
})

Note that with axios I had to use the content-type.

Spring Data JPA - "No Property Found for Type" Exception

I had this exception recently when moving to a newer spring-boot version (from 1.5.4 to 1.5.20). The problem was in the repository package structure.

Problem: Under the same package were packages: repository, repositoryCustom and repositoryImpl.

Solution: Rearrange repository packages so that repository package contains repositoryCustom package and repositoryCustom package contains repositoryImpl:

repository 
   |
   ----- repositoryCustom
             |
             ----- repositoryImpl

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

How can you make a custom keyboard in Android?

Use KeyboardView:

KeyboardView kbd = new KeyboardView(context);
kbd.setKeyboard(new Keyboard(this, R.xml.custom));

kbd.setOnKeyboardActionListener(new OnKeyboardActionListener() {
    ....
}

now you have kbd which is a normal view.

The nice thing about this is that R.xml.custom refers to /res/xml/custom.xml, which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.

Call multiple functions onClick ReactJS

Maybe you can use arrow function (ES6+) or the simple old function declaration.

Normal function declaration type (Not ES6+):

<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>

Anonymous function or arrow function type (ES6+)

<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>

The second one is the shortest road that I know. Hope it helps you!

Palindrome check in Javascript

Thought I will share my solution using Array.prototype.filter(). filter() filters the array based on boolean values the function returns.

var inputArray=["","a","ab","aba","abab","ababa"]
var outputArray=inputArray.filter(function isPalindrome(x){
  if (x.length<2) return true;
  var y=x.split("").reverse().join("");
  return x==y;
})
console.log(outputArray);

Currency Formatting in JavaScript

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

How to link C++ program with Boost using CMake

Here is my take:

cmake_minimum_required(VERSION 3.15)

project(TryOuts LANGUAGES CXX)

find_package(Boost QUIET REQUIRED COMPONENTS program_options)

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
endif()

add_executable(helloworld main.cpp)

target_link_libraries(helloworld PUBLIC Boost::program_options)

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

What's the difference between size_t and int in C++?

The definition of SIZE_T is found at: https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx

Pasting here the required information:

SIZE_T is a ULONG_PTR representing the maximum number of bytes to which a pointer can point.

This type is declared as follows:

typedef ULONG_PTR SIZE_T;

A ULONG_PTR is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.

This type is declared as follows:

typedef unsigned __int3264 ULONG_PTR;

R: rJava package install failing

On Arch Linux, I needed to install openjdk-src to get a JNI path working.

In other words, these are the packages I needed to install before sudo R CMD javareconf ran successfully:

local/jdk-openjdk 14.0.2.u12-1
    OpenJDK Java 14 development kit
local/jre-openjdk 14.0.2.u12-1
    OpenJDK Java 14 full runtime environment
local/jre-openjdk-headless 14.0.2.u12-1
    OpenJDK Java 14 headless runtime environment
local/openjdk-src 14.0.2.u12-1
    OpenJDK Java 14 sources

get the margin size of an element with jquery

From jQuery's website

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

Determine if an element has a CSS class with jQuery

Use the hasClass method:

jQueryCollection.hasClass(className);

or

$(selector).hasClass(className);

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,

<span class="foo bar" />

then this will return true:

$('span').hasClass('foo bar')

and these will return false:

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')

How to install VS2015 Community Edition offline

You can download the ISO from https://beta.visualstudio.com/downloads/ (even if it has "beta" in the URL you'll have the latest stable version. Currently update 3)

VS2015 Community download

How do I schedule a task to run at periodic intervals?

timer.scheduleAtFixedRate( new Task(), 1000,3000); 

How to preview an image before and after upload?

On input type=file add an event onchange="preview()"

For the function preview() type:

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

_x000D_
_x000D_
function preview() {
   thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
    <input type="file" onchange="preview()">
    <img id="thumb" src="" width="150px"/>
</form>
_x000D_
_x000D_
_x000D_

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

I was facing the same error, and look what I was doing. My bad, I was trying to add the same view NativeAdView to the multiple FrameLayouts, resolved by creating a separate view NativeAdView for each FrameLayout, Thanks

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Fixed a few typos in the working code above:

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("[email protected]", "SomeOne"));
msg.From = new MailAddress("[email protected]", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
    client.Send(msg);
    lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
    lblText.Text = ex.ToString();
}

I have two web applications using the above code and both work fine without any trouble.

How do I concatenate two strings in Java?

Use + for string concatenation.

"Your number is " + theNumber + "!"

Can I check if Bootstrap Modal Shown / Hidden?

if($('.modal').hasClass('in')) {
    alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
    alert("No pop-up opened");
}

Declare and Initialize String Array in VBA

Using

Dim myarray As Variant

works but

Dim myarray As String

doesn't so I sitck to Variant

Delete all local git branches

Just a note, I would upgrade to git 1.7.10. You may be getting answers here that won't work on your version. My guess is that you would have to prefix the branch name with refs/heads/.

CAUTION, proceed with the following only if you made a copy of your working folder and .git directory.

I sometimes just go ahead and delete the branches I don't want straight from .git/refs/heads. All these branches are text files that contain the 40 character sha-1 of the commit they point to. You will have extraneous information in your .git/config if you had specific tracking set up for any of them. You can delete those entries manually as well.

SQL Server 2008 R2 can't connect to local database in Management Studio

I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).

Calculate distance between two latitude-longitude points? (Haversine formula)

This link might be helpful to you, as it details the use of the Haversine formula to calculate the distance.

Excerpt:

This script [in Javascript] calculates great-circle distances between the two points – that is, the shortest distance over the earth’s surface – using the ‘Haversine’ formula.

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

Cross field validation with Hibernate Validator (JSR 303)

You guys are awesome. Really amazing ideas. I like Alberthoven's and McGin's most, so I decided to combine both ideas. And develop some generic solution to cater all cases. Here is my proposed solution.

@Documented
@Constraint(validatedBy = NotFalseValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotFalse {


    String message() default "NotFalse";
    String[] messages();
    String[] properties();
    String[] verifiers();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

public class NotFalseValidator implements ConstraintValidator<NotFalse, Object> {
    private String[] properties;
    private String[] messages;
    private String[] verifiers;
    @Override
    public void initialize(NotFalse flag) {
        properties = flag.properties();
        messages = flag.messages();
        verifiers = flag.verifiers();
    }

    @Override
    public boolean isValid(Object bean, ConstraintValidatorContext cxt) {
        if(bean == null) {
            return true;
        }

        boolean valid = true;
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);

        for(int i = 0; i< properties.length; i++) {
           Boolean verified = (Boolean) beanWrapper.getPropertyValue(verifiers[i]);
           valid &= isValidProperty(verified,messages[i],properties[i],cxt);
        }

        return valid;
    }

    boolean isValidProperty(Boolean flag,String message, String property, ConstraintValidatorContext cxt) {
        if(flag == null || flag) {
            return true;
        } else {
            cxt.disableDefaultConstraintViolation();
            cxt.buildConstraintViolationWithTemplate(message)
                    .addPropertyNode(property)
                    .addConstraintViolation();
            return false;
        }

    }



}

@NotFalse(
        messages = {"End Date Before Start Date" , "Start Date Before End Date" } ,
        properties={"endDateTime" , "startDateTime"},
        verifiers = {"validDateRange" , "validDateRange"})
public class SyncSessionDTO implements ControllableNode {
    @NotEmpty @NotPastDate
    private Date startDateTime;

    @NotEmpty
    private Date endDateTime;



    public Date getStartDateTime() {
        return startDateTime;
    }

    public void setStartDateTime(Date startDateTime) {
        this.startDateTime = startDateTime;
    }

    public Date getEndDateTime() {
        return endDateTime;
    }

    public void setEndDateTime(Date endDateTime) {
        this.endDateTime = endDateTime;
    }


    public Boolean getValidDateRange(){
        if(startDateTime != null && endDateTime != null) {
            return startDateTime.getTime() <= endDateTime.getTime();
        }

        return null;
    }

}

Eclipse count lines of code

One possible way to count lines of code in Eclipse:

using the Search / File... menu, select File Search tab, specify \n[\s]* for Containing text (this will not count empty lines), and tick Regular expression.

Hat tip: www.monblocnotes.com/node/2030

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

PyLint "Unable to import" error - how to set PYTHONPATH?

There are two options I'm aware of.

One, change the PYTHONPATH environment variable to include the directory above your module.

Alternatively, edit ~/.pylintrc to include the directory above your module, like this:

[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'

(Or in other version of pylint, the init-hook requires you to change [General] to [MASTER])

Both of these options ought to work.

Hope that helps.

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

How to make a div fill a remaining horizontal space?

If you don't need compatibility with older versions of certain browsers (IE 10 8 or less for example) you can use the calc() CSS function:

#left {
   float:left;
   width:180px;
   background-color:#ff0000;
}

#right {
   float: left;
   width: calc(100% - 180px);
   background-color:#00FF00;
}

Opacity CSS not working in IE8

here is the answer for IE 8

AND IT WORKS for alpha to work in IE8 you have to use position atribute for that element like

position:relative or other.

http://www.codingforums.com/showthread.php?p=923730

How to set Java classpath in Linux?

You have to use ':' colon instead of ';' semicolon.

As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.

And the variable must be CLASSPATH not classpath.

How to add multiple font files for the same font?

/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'), /* Duplicated name with hyphen */
        url('dejavu/DejaVuSans.ttf') 
        format('truetype');
}
/*bold version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Bold.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Bold.ttf') 
        format('truetype');
    font-weight: bold;
}
/*italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Oblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Oblique.ttf') 
        format('truetype');
    font-style: italic;
}
/*bold italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-BoldOblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-BoldOblique.ttf') 
        format('truetype');
    font-weight: bold;
    font-style: italic;
}

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Be consistent! JOIN-ing a VARCHAR to NVARCHAR has a big performance hit.