Programs & Examples On #Graph layout

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

How to get the azure account tenant Id?

Time changes everything. I was looking to do the same recently and came up with this:

Note

added 02/17/2021

Stable Portal Page thanks Palec

added 12/18/2017

As indicated by shadowbq, the DirectoryId and TenantId both equate to the GUID representing the ActiveDirectory Tenant. Depending on context, either term may be used by Microsoft documentation and products, which can be confusing.

Assumptions

  • You have access to the Azure Portal

Solution

The tenant ID is tied to ActiveDirectoy in Azure

  • Navigate to Dashboard
  • Navigate to ActiveDirectory
  • Navigate to Manage / Properties
  • Copy the "Directory ID"

Azure ActiveDirectory Tenant ID

Yes I used paint, don't judge me.

PHP refresh window? equivalent to F5 page reload?

<?php 
echo "<script>window.opener.location.reload();</script>";
echo "<script>window.close();</script>";
?>

CSS: Auto resize div to fit container width

I have updated your jsfiddle and here is CSS changes you need to do:

#content
{
    min-width:700px;
    margin-right: -210px;
    width:100%;
    float:left;
    background-color:AppWorkspace;
}

How to do multiple arguments to map function where one remains the same in python?

Another option is:

results = []
for x in [1,2,3]:
    z = add(x,2)
    ...
    results += [f(z,x,y)]

This format is very useful when calling multiple functions.

Send a SMS via intent

If you want a certain message, use this:

String phoneNo = "";//The phone number you want to text
String sms= "";//The message you want to text to the phone

Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phoneNo, null));
smsIntent.putExtra("sms_body",sms);
startActivity(smsIntent);

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

How do I pause my shell script for a second before continuing?

Run multiple sleeps and commands

sleep 5 && cd /var/www/html && git pull && sleep 3 && cd ..

This will wait for 5 seconds before executing the first script, then will sleep again for 3 seconds before it changes directory again.

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

PHP import Excel into database (xls & xlsx)

If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:

load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>

What is the C# equivalent of NaN or IsNumeric?

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

What are the best use cases for Akka framework

We use Akka in several projects at work, the most interesting of which is related to vehicle crash repair. Primarily in the UK but now expanding to the US, Asia, Australasia and Europe. We use actors to ensure that crash repair information is provided realtime to enable the safe and cost effective repair of vehicles.

The question with Akka is really more 'what can't you do with Akka'. Its ability to integrate with powerful frameworks, its powerful abstraction and all of the fault tolerance aspects make it a very comprehensive toolkit.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

In javascript, how do you search an array for a substring match

If you're able to use Underscore.js in your project, the _.filter() array function makes this a snap:

// find all strings in array containing 'thi'
var matches = _.filter(
    [ 'item 1', 'thing', 'id-3-text', 'class' ],
    function( s ) { return s.indexOf( 'thi' ) !== -1; }
);

The iterator function can do whatever you want as long as it returns true for matches. Works great.

Update 2017-12-03:
This is a pretty outdated answer now. Maybe not the most performant option in a large batch, but it can be written a lot more tersely and use native ES6 Array/String methods like .filter() and .includes() now:

// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));

Note: There's no <= IE11 support for String.prototype.includes() (Edge works, mind you), but you're fine with a polyfill, or just fall back to indexOf().

Notepad++ incrementally replace

Since there are limited real answers I'll share this workaround. For really simple cases like your example you do it backwards...

From this

1
2
3
4
5

Replace \r\n with " />\r\n<row id=" and you'll get 90% of the way there

1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5

Or is a similar fashion you can hack about data with excel/spreadsheet. Just split your original data into columns and manipulate values as you require.

|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |

Obvious stuff but it may help someone doing the odd one-off hack job to save a few key strokes.

CSS @font-face not working in ie

You could use the Google Font API. They say it works from IE 6 and up. (I've not tested this.)

Google’s serving infrastructure takes care of converting the font into a format compatible with any modern browser (including Internet Explorer 6 and up), ...

How can I count the occurrences of a list item?

Why not using Pandas?

import pandas as pd

l = ['a', 'b', 'c', 'd', 'a', 'd', 'a']

# converting the list to a Series and counting the values
my_count = pd.Series(l).value_counts()
my_count

Output:

a    3
d    2
b    1
c    1
dtype: int64

If you are looking for a count of a particular element, say a, try:

my_count['a']

Output:

3

What is the best way to seed a database in Rails?

Using seeds.rb file or FactoryBot is great, but these are respectively great for fixed data structures and testing.

The seedbank gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):

rake db:seed                    # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar                # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common             # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development        # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users  # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo                # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original           # Load the seed data from db/seeds.rb

Parsing a CSV file using NodeJS

The node-csv project that you are referencing is completely sufficient for the task of transforming each row of a large portion of CSV data, from the docs at: http://csv.adaltas.com/transform/:

csv()
  .from('82,Preisner,Zbigniew\n94,Gainsbourg,Serge')
  .to(console.log)
  .transform(function(row, index, callback){
    process.nextTick(function(){
      callback(null, row.reverse());
    });
});

From my experience, I can say that it is also a rather fast implementation, I have been working with it on data sets with near 10k records and the processing times were at a reasonable tens-of-milliseconds level for the whole set.

Rearding jurka's stream based solution suggestion: node-csv IS stream based and follows the Node.js' streaming API.

Is there an easy way to return a string repeated X number of times?

I didn't see this solution. I find it simpler for where I currently am in software development:

public static void PrintFigure(int shapeSize)
{
    string figure = "\\/";
    for (int loopTwo = 1; loopTwo <= shapeSize - 1; loopTwo++)
    {
        Console.Write($"{figure}");
    }
}

how to check if input field is empty

use .val(), it will return the value of the <input>

$("#spa").val().length > 0

And you had a typo, length not lenght.

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

Adding local .aar files to Gradle build using "flatDirs" is not working

Update : As @amram99 mentioned, the issue has been fixed as of the release of Android Studio v1.3.

Tested and verified with below specifications

  • Android Studio v1.3
  • gradle plugin v1.2.3
  • Gradle v2.4

What works now

  • Now you can import a local aar file via the File>New>New Module>Import .JAR/.AAR Package option in Android Studio v1.3

  • However the below answer holds true and effective irrespective of the Android Studio changes as this is based of gradle scripting.


Old Answer : In a recent update the people at android broke the inclusion of local aar files via the Android Studio's add new module menu option. Check the Issue listed here. Irrespective of anything that goes in and out of IDE's feature list , the below method works when it comes to working with local aar files.(Tested it today):

Put the aar file in the libs directory (create it if needed), then, add the following code in your build.gradle :

dependencies {
   compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar')
 }
repositories{
      flatDir{
              dirs 'libs'
       }
 }

Chrome says my extension's manifest file is missing or unreadable

Some permissions issue for default sample.

I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.

Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip

which can be found at
https://developer.chrome.com/extensions/samples

this worked great, hope it helps

Loop through all the resources in a .resx file

Use ResXResourceReader Class

ResXResourceReader rsxr = new ResXResourceReader("your resource file path");

// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
    Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Padding is an operation to increase the size of the input data. In case of 1-dimensional data you just append/prepend the array with a constant, in 2-dim you surround matrix with these constants. In n-dim you surround your n-dim hypercube with the constant. In most of the cases this constant is zero and it is called zero-padding.

Here is an example of zero-padding with p=1 applied to 2-d tensor: enter image description here


You can use arbitrary padding for your kernel but some of the padding values are used more frequently than others they are:

  • VALID padding. The easiest case, means no padding at all. Just leave your data the same it was.
  • SAME padding sometimes called HALF padding. It is called SAME because for a convolution with a stride=1, (or for pooling) it should produce output of the same size as the input. It is called HALF because for a kernel of size k enter image description here
  • FULL padding is the maximum padding which does not result in a convolution over just padded elements. For a kernel of size k, this padding is equal to k - 1.

To use arbitrary padding in TF, you can use tf.pad()

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Count the number of occurrences of a string in a VARCHAR field?

Here is a function that will do that.

CREATE FUNCTION count_str(haystack TEXT, needle VARCHAR(32))
  RETURNS INTEGER DETERMINISTIC
  BEGIN
    RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
  END;

Remove all html tags from php string

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

Or if you have a content coming from the database;

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

How to uncheck a radio button?

$('#frm input[type="radio":checked]').each(function(){
   $(this).checked = false;  
  });

This is almost good but you missed the [0]

Correct ->> $(this)[0].checked = false;

youtube: link to display HD video by default

Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.

Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080

What you get as a result is the standalone 1080p video but not in the Tube environment.

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Generating UNIQUE Random Numbers within a range

The "shuffle" method has a MAJOR FALW. When the numbers are big, shuffle 3 billion indexs will instantly CAUSE 500 error. Here comes a best solution for really big numbers.

function getRandomNumbers($min, $max, $total) {
    $temp_arr = array();
    while(sizeof($temp_arr) < $total) $temp_arr[rand($min, $max)] = true;
    return $temp_arr;
}

Say I want to get 10 unique random numbers from 1 billion to 4 billion.

$random_numbers = getRandomNumbers(1000000000,4000000000,10);

PS: Execution time: 0.027 microseconds

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You are "tainting" the canvas by loading from a cross origins domain. Check out this MDN article:

https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()

{this.renderIcon()}   

Spring Boot - Loading Initial Data

As suggestion try this:

@Bean
public CommandLineRunner loadData(CustomerRepository repository) {
    return (args) -> {
        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            log.info(customer.toString());
        }
        log.info("");

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        log.info("Customer found with findOne(1L):");
        log.info("--------------------------------");
        log.info(customer.toString());
        log.info("");

        // fetch customers by last name
        log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
        log.info("--------------------------------------------");
        for (Customer bauer : repository
                .findByLastNameStartsWithIgnoreCase("Bauer")) {
            log.info(bauer.toString());
        }
        log.info("");
    }
}

Option 2: Initialize with schema and data scripts

Prerequisites: in application.properties you have to mention this:

spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)

Then, in your MyApplication class paste this:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // schema init
    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
    Resource initData = new ClassPathResource("scripts/data-h2.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

    return dataSource;
}

Where scripts folder is located under resources folder (IntelliJ Idea)

Hope it helps someone

beyond top level package error in relative import

In my humble opinion, I understand this question in this way:

[CASE 1] When you start an absolute-import like

python -m test_A.test

or

import test_A.test

or

from test_A import test

you're actually setting the import-anchor to be test_A, in other word, top-level package is test_A . So, when we have test.py do from ..A import xxx, you are escaping from the anchor, and Python does not allow this.

[CASE 2] When you do

python -m package.test_A.test

or

from package.test_A import test

your anchor becomes package, so package/test_A/test.py doing from ..A import xxx does not escape the anchor(still inside package folder), and Python happily accepts this.

In short:

  • Absolute-import changes current anchor (=redefines what is the top-level package);
  • Relative-import does not change the anchor but confines to it.

Furthermore, we can use full-qualified module name(FQMN) to inspect this problem.

Check FQMN in each case:

  • [CASE2] test.__name__ = package.test_A.test
  • [CASE1] test.__name__ = test_A.test

So, for CASE2, an from .. import xxx will result in a new module with FQMN=package.xxx, which is acceptable.

While for CASE1, the .. from within from .. import xxx will jump out of the starting node(anchor) of test_A, and this is NOT allowed by Python.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

As @Jthorpe alluded to, ComponentClass only allows either Component or PureComponent but not a FunctionComponent.

If you attempt to pass a FunctionComponent, typescript will throw an error similar to...

Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.

However, by using ComponentType rather than ComponentClass you allow for both cases. Per the react declaration file the type is defined as...

type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

'tsc command not found' in compiling typescript

Easy fix for Mac I found. Just run these commands:

sudo npm install -g concurrently
sudo npm install -g lite-server
sudo npm install -g typescript

Nothing worked except this for me.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

A short example will help you understand one of yield from's use case: get value from another generator

def flatten(sequence):
    """flatten a multi level list or something
    >>> list(flatten([1, [2], 3]))
    [1, 2, 3]
    >>> list(flatten([1, [2], [3, [4]]]))
    [1, 2, 3, 4]
    """
    for element in sequence:
        if hasattr(element, '__iter__'):
            yield from flatten(element)
        else:
            yield element

print(list(flatten([1, [2], [3, [4]]])))

Didn't Java once have a Pair class?

There are lots of implementation around here, but all the time something is missing , the Override of equal and hash method.

here is a more complete version of this class:

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair<F, S> {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}

Bash script processing limited number of commands in parallel

In fact, xargs can run commands in parallel for you. There is a special -P max_procs command-line option for that. See man xargs.

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

(13: Permission denied) while connecting to upstream:[nginx]

  1. Check the user in /etc/nginx/nginx.conf
  2. Change ownership to user.
sudo chown -R nginx:nginx /var/lib/nginx

Now see the magic.

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

make *** no targets specified and no makefile found. stop

make takes a makefile as input. Makefile usually is named makefile or Makefile. The configure command should generate a makefile, so that make could be in turn executed. Check if a makefile has been generated under your working directory.

Xcode 4: How do you view the console?

Here's an alternative.

  1. In XCode4 double-click your Project (Blueprint Icon).
  2. Select the Target (Gray Icon)
  3. Select the Build Phases (Top Center)
  4. Add Build Phase "Run Script" (Green Plus Button, bottom right)
  5. In the textbox below the Shell textfield replace "Type a script or drag a script file from your workspace" with "open ${TARGET_BUILD_DIR}/${TARGET_NAME}"

This will open a terminal window with your command-line app running in it.

This is not a great solution because XCode 4 still runs and debugs the app independently of what you're doing in the terminal window that pops up.

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

Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheaper to use a try statement:

urls_d = {}
for url in list_of_urls:
    try:
        urls_d[url] += 1
    except KeyError:
        urls_d[url] = 1

you can read more about this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips

JFrame.dispose() vs System.exit()

In addition to the above you can use the System.exit() to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code); this can help you determine for example if an error has occured during the run.

Optimal number of threads per core

If your threads don't do I/O, synchronization, etc., and there's nothing else running, 1 thread per core will get you the best performance. However that very likely not the case. Adding more threads usually helps, but after some point, they cause some performance degradation.

Not long ago, I was doing performance testing on a 2 quad-core machine running an ASP.NET application on Mono under a pretty decent load. We played with the minimum and maximum number of threads and in the end we found out that for that particular application in that particular configuration the best throughput was somewhere between 36 and 40 threads. Anything outside those boundaries performed worse. Lesson learned? If I were you, I would test with different number of threads until you find the right number for your application.

One thing for sure: 4k threads will take longer. That's a lot of context switches.

How to put Google Maps V2 on a Fragment using ViewPager

The following approach works for me.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

    // Perform any camera updates here
    return v;
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}

fragment_location_info.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

T-SQL to list all the user mappings with database roles/permissions for a Login

Did you sort this? I just found this code here:

http://www.pythian.com/news/29665/httpconsultingblogs-emc-comjamiethomsonarchive20070209sql-server-2005_3a00_-view-all-permissions-_2800_2_2900_-aspx/

I think I'll need to do a bit of tweaking, but essentially this has sorted it for me!

I hope it does for you too!

J

Running command line silently with VbScript and getting output?

I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:

cscript myscript.vbs //nologo

any .Exec() calls in the myscript.vbs do not open an extra window, meaning that you can use the first variant of your original solution (using exec).

(Note that the two forward slashes in the above code are intentional, see cscript /?)

List all files from a directory recursively with Java

import java.io.*;

public class MultiFolderReading {

public void checkNoOfFiles (String filename) throws IOException {

    File dir=new File(filename);
    File files[]=dir.listFiles();//files array stores the list of files

 for(int i=0;i<files.length;i++)
    {
        if(files[i].isFile()) //check whether files[i] is file or directory
        {
            System.out.println("File::"+files[i].getName());
            System.out.println();

        }
        else if(files[i].isDirectory())
        {
            System.out.println("Directory::"+files[i].getName());
            System.out.println();
            checkNoOfFiles(files[i].getAbsolutePath());
        }
    }
}

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

    MultiFolderReading mf=new MultiFolderReading();
    String str="E:\\file"; 
    mf.checkNoOfFiles(str);
   }
}

Select N random elements from a List<T> in C#

You can use this but the ordering will happen on client side

 .AsEnumerable().OrderBy(n => Guid.NewGuid()).Take(5);

Getting a slice of keys from a map

I made a sketchy benchmark on the three methods described in other responses.

Obviously pre-allocating the slice before pulling the keys is faster than appending, but surprisingly, the reflect.ValueOf(m).MapKeys() method is significantly slower than the latter:

? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s

Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)

Maximum on http header values?

As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).

It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:

pagesize.c:

#include <unistd.h>
#include <stdio.h>

int main() {
    int pageSize = getpagesize();
    printf("Page size on your system = %i bytes\n", pageSize);
    return 0;
}

Compile with gcc -o pagesize pagesize.c then run ./pagesize. My ubuntu server from Linode dutifully informs me the answer is 4k.

Oracle database: How to read a BLOB?

What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?

And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.

I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.

Java keytool easy way to add server cert from url/port

Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.

#!/usr/bin/env sh

KEYSTORE_FILE=/path/to/keystore.jks
KEYSTORE_PASS=changeit


import_cert() {
  local HOST=$1
  local PORT=$2

  # get the SSL certificate
  openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

  # delete the old alias and then import the new one
  keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null

  # create a keystore and import certificate
  keytool -import -noprompt -trustcacerts \
      -alias ${HOST} -file ${HOST}.cert \
      -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}

  rm ${HOST}.cert
}

import_cert stackoverflow.com 443
import_cert www.google.com 443
import_cert 172.217.194.104 443 # google

Find PHP version on windows command line

For Beginners to anything php, it is usually stored in the C:/ path folder of your PC (My Computer).

==On Windows==
1.Click Start Menu button
2.Type cmd and press enter to select the first program/application that responds to your search result.
A black window terminal will appear, this is known as a Command Line Interpreter
3.In the Terminal Window (Application) Type cd c: and press enter
4.Now type php -v and press enter

and viola there you'll have the current php version that is installed in your machine

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

How do I upgrade to Python 3.6 with conda?

I'm using a Mac OS Mojave

These 4 steps worked for me.

  1. conda update conda
  2. conda install python=3.6
  3. conda install anaconda-client
  4. conda update anaconda

How to write log base(2) in c/c++

As stated on http://en.wikipedia.org/wiki/Logarithm:

logb(x) = logk(x) / logk(b)

Which means that:

log2(x) = log10(x) / log10(2)

A server with the specified hostname could not be found

Just to share my experience

It was caused by the Sharing > Internet Sharing inside System Preferences

I was testing and created NAT64 Network unchecking it solved my problem.

enter image description here

How to view file history in Git?

Of course, if you want something as close to TortoiseSVN as possible, you could just use TortoiseGit.

Oracle Convert Seconds to Hours:Minutes:Seconds

For greater than 24 hours you can include days with the following query. The returned format is days:hh24:mi:ss

Query:
select trunc(trunc(sysdate) + numtodsinterval(9999999, 'second')) - trunc(sysdate) || ':' || to_char(trunc(sysdate) + numtodsinterval(9999999, 'second'), 'hh24:mi:ss') from dual;

Output:
115:17:46:39

Convert a date format in epoch

Create Common Method to Convert String to Date format

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}

Threads vs Processes in Linux

For most cases i would prefer processes over threads. threads can be useful when you have a relatively smaller task (process overhead >> time taken by each divided task unit) and there is a need of memory sharing between them. Think a large array. Also (offtopic), note that if your CPU utilization is 100 percent or close to it, there is going to be no benefit out of multithreading or processing. (in fact it will worsen)

Exception 'open failed: EACCES (Permission denied)' on Android

In my case I was using a file picker library which returned the path to external storage but it started from /root/. And even with the WRITE_EXTERNAL_STORAGE permission granted at runtime I still got error EACCES (Permission denied).
So use Environment.getExternalStorageDirectory() to get the correct path to external storage.

Example:
Cannot write: /root/storage/emulated/0/newfile.txt
Can write: /storage/emulated/0/newfile.txt

boolean externalStorageWritable = isExternalStorageWritable();
File file = new File(filePath);
boolean canWrite = file.canWrite();
boolean isFile = file.isFile();
long usableSpace = file.getUsableSpace();

Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
Log.d(TAG, "filePath: " + filePath);
Log.d(TAG, "canWrite: " + canWrite);
Log.d(TAG, "isFile: " + isFile);
Log.d(TAG, "usableSpace: " + usableSpace);

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

Output 1:

externalStorageWritable: true
filePath: /root/storage/emulated/0/newfile.txt
isFile: false
usableSpace: 0

Output 2:

externalStorageWritable: true
filePath: /storage/emulated/0/newfile.txt
isFile: true
usableSpace: 1331007488

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Another way (credit):

@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @( 
    Set Month=%%A
    Set Day=%%B
    Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.

Find a value in an array of objects in Javascript

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);

Error 1022 - Can't write; duplicate key in table

This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.

A fix was released in 2.3.0.

See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.

How to block users from closing a window in Javascript?

Take a look at onBeforeUnload.

It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

Edit: Most browsers no longer allow a custom message for onbeforeunload.

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.

In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.

Firefox already does this[...]

creating list of objects in Javascript

Going off of tbradley22's answer, but using .map instead:

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

Should have subtitle controller already set Mediaplayer error Android

To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

Escaping ampersand character in SQL string

straight from oracle sql fundamentals book

SET DEFINE OFF
select 'Coda & Sid' from dual;
SET DEFINE ON

how would one escape it without setting define.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Up above, you mention having compiling your as part of your steps to reproduce, but then below you made an edit saying,

"is there a way to see on which distro a shared library was compiled on?"

Whether or not you compiled this on the same distro, and even a different version of the same distro is an important detail, especially for c++ applications.

Linking to c++ libraries, including libstdc++ can have mixed results, as far as I can tell. Here is a related question about recompiling with different versions of c++.

do we need to recompile libraries with c++11?

Basically, if you compiled against c++ on a different distro (and possibly different gcc version), this may be causing your trouble.

I think you have two options:

  1. Your best bet - recompile your .so if you hadn't compiled it on your current system. If there is a problem with your runtime's system environment, it might even come out in the compile.
  2. Bundle your other compiler's c++ libs along with your application. This may only be viable if it's the same distribution... But it's a useful trick if you rolled your own compiler. You will also have to set and export the LD_LIBRARY_PATH to the path containing your bundled stdc++ libs if you go that route.

Calculate the execution time of a method

StopWatch class looks for your best solution.

Stopwatch sw = Stopwatch.StartNew();
DoSomeWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

Also it has a static field called Stopwatch.IsHighResolution. Of course, this is a hardware and operating system issue.

Indicates whether the timer is based on a high-resolution performance counter.

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

c# foreach (property in object)... Is there a simple way of doing this?

A copy-paste solution (extension methods) mostly based on earlier responses to this question.

Also properly handles IDicitonary (ExpandoObject/dynamic) which is often needed when dealing with this reflected stuff.

Not recommended for use in tight loops and other hot paths. In those cases you're gonna need some caching/IL emit/expression tree compilation.

    public static IEnumerable<(string Name, object Value)> GetProperties(this object src)
    {
        if (src is IDictionary<string, object> dictionary)
        {
            return dictionary.Select(x => (x.Key, x.Value));
        }
        return src.GetObjectProperties().Select(x => (x.Name, x.GetValue(src)));
    }

    public static IEnumerable<PropertyInfo> GetObjectProperties(this object src)
    {
        return src.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => !p.GetGetMethod().GetParameters().Any());
    }

Using openssl to get the certificate from a server

The easiest command line for this, which includes the PEM output to add it to the keystore, as well as a human readable output and also supports SNI, which is important if you are working with an HTTP server is:

openssl s_client -servername example.com -connect example.com:443 \
    </dev/null 2>/dev/null | openssl x509 -text

The -servername option is to enable SNI support and the openssl x509 -text prints the certificate in human readable format.

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

Equivalent of Math.Min & Math.Max for Dates?

Now that we have LINQ, you can create an array with your two values (DateTimes, TimeSpans, whatever) and then use the .Max() extension method.

var values = new[] { Date1, Date2 }; 
var max = values.Max(); 

It reads nice, it's as efficient as Max can be, and it's reusable for more than 2 values of comparison.

The whole problem below worrying about .Kind is a big deal... but I avoid that by never working in local times, ever. If I have something important regarding times, I always work in UTC, even if it means more work to get there.

How do I get the full path of the current file's directory?

import os
print os.path.dirname(__file__)

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Console.WriteLine and generic List

        List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
        a.ForEach(p => Console.WriteLine(p));

edit: ahhh he beat me to it.

How can I get enum possible values in a MySQL database?

A more up to date way of doing it, this worked for me:

function enum_to_array($table, $field) {    
    $query = "SHOW FIELDS FROM `{$table}` LIKE '{$field}'";
    $result = $db->query($sql);
    $row = $result->fetchRow();
    preg_match('#^enum\((.*?)\)$#ism', $row['Type'], $matches);
    $enum = str_getcsv($matches[1], ",", "'");
    return $enum;
}

Ultimately, the enum values when separated from "enum()" is just a CSV string, so parse it as such!

Google Maps JavaScript API RefererNotAllowedMapError

  1. That your billing is enabled

  2. That your website has been added to Google Console

  3. That your website is added to the referrers in your app.

  4. (do a wildcard for both www and none www)

http://www.example.com/* and http://example.com/*

  1. That Javascript Maps is enabled and you are using the correct credentials

  2. That the website has been added to your DNS to enable your Google Console above.

  3. Smile after it works!

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

ECLIPSE PHOTON ON MAC

  1. Get your current JAVA_HOME path /Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home

  2. open /Users/you/eclipse/jee-photon/Eclipse.app/Contents/Eclipse/ and click on package content. Then open eclipse.ini file using any text file editor.

  3. Edit your -VM argument as below( Make sure the Java Path is same as $JAVA_HOME)

-vm

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/bin

  1. save and start your eclipse.

Ruby on Rails: Clear a cached page

If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:

Version #1

<% cache ['cool_name_for_cache_key', 'v1'] do %>

Version #2

<% cache ['cool_name_for_cache_key', 'v2'] do %>

Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:

<% cache @user_object do %>

With this ^ method, any time the user object is updated, the cache will automatically be reset.

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

Should I always use a parallel stream when possible?

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if

  • I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)

  • I have a performance problem in the first place

  • I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)

In your example, the performance will anyway be driven by the synchronized access to System.out.println(), and making this process parallel will have no effect, or even a negative one.

Moreover, remember that parallel streams don't magically solve all the synchronization problems. If a shared resource is used by the predicates and functions used in the process, you'll have to make sure that everything is thread-safe. In particular, side effects are things you really have to worry about if you go parallel.

In any case, measure, don't guess! Only a measurement will tell you if the parallelism is worth it or not.

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

Plot a horizontal line using matplotlib

In addition to the most upvoted answer here, one can also chain axhline after calling plot on a pandas's DataFrame.

import pandas as pd

(pd.DataFrame([1, 2, 3])
   .plot(kind='bar', color='orange')
   .axhline(y=1.5));

enter image description here

How to add a custom button to the toolbar that calls a JavaScript function?

This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal

There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.

How can I programmatically get the MAC address of an iphone

I wanted something to return the address regardless of whether or not wifi was enabled, so the chosen solution didn't work for me. I used another call I found on some forum after some tweaking. I ended up with the following (excuse my rusty C ) :

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>


char*  getMacAddress(char* macAddress, char* ifName) {

int  success;
struct ifaddrs * addrs;
struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const unsigned char* base;
int i;

success = getifaddrs(&addrs) == 0;
if (success) {
    cursor = addrs;
    while (cursor != 0) {
        if ( (cursor->ifa_addr->sa_family == AF_LINK)
            && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp(ifName,  cursor->ifa_name)==0 ) {
            dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
            base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
            strcpy(macAddress, ""); 
            for (i = 0; i < dlAddr->sdl_alen; i++) {
                if (i != 0) {
                    strcat(macAddress, ":");
                }
                char partialAddr[3];
                sprintf(partialAddr, "%02X", base[i]);
                strcat(macAddress, partialAddr);

            }
        }
        cursor = cursor->ifa_next;
    }

    freeifaddrs(addrs);
}    
return macAddress;
}

And then I would call it asking for en0, as follows:

char* macAddressString= (char*)malloc(18);
NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString, "en0")
                                              encoding:NSMacOSRomanStringEncoding];
free(macAddressString);

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

Python json.loads shows ValueError: Extra data

I think saving dicts in a list is not an ideal solution here proposed by @falsetru.

Better way is, iterating through dicts and saving them to .json by adding a new line.

our 2 dictionaries are

d1 = {'a':1}

d2 = {'b':2}

you can write them to .json

import json
with open('sample.json','a') as sample:
    for dict in [d1,d2]:
        sample.write('{}\n'.format(json.dumps(dict)))

and you can read json file without any issues

with open('sample.json','r') as sample:
    for line in sample:
        line = json.loads(line.strip())

simple and efficient

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04
==============================================================================

Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

Get the last non-empty cell in a column in Google Sheets

To find the last non-empty cell you can use INDEX and MATCH functions like this:

=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))

I think this is a little bit faster and easier.

Can I loop through a table variable in T-SQL?

Here's another answer, similar to Justin's, but doesn't need an identity or aggregate, just a primary (unique) key.

declare @table1 table(dataKey int, dataCol1 varchar(20), dataCol2 datetime)
declare @dataKey int
while exists select 'x' from @table1
begin
    select top 1 @dataKey = dataKey 
    from @table1 
    order by /*whatever you want:*/ dataCol2 desc

    -- do processing

    delete from @table1 where dataKey = @dataKey
end

How to analyse the heap dump using jmap in java

Very late to answer this, but worth to take a quick look at. Just 2 minutes needed to understand in detail.

First create this java program

import java.util.ArrayList;
import java.util.List;

public class GarbageCollectionAnalysisExample{
    public static void main(String[] args) {
           List<String> l = new ArrayList<String>();
           for (int i = 0; i < 100000000; i++) {
                  l = new ArrayList<String>(); //Memory leak
                  System.out.println(l);
           }
           System.out.println("Done");
    }
}

Use jps to find the vmid (virtual machine id i.e. JVM id)

Go to CMD and type below commands >

C:\>jps
18588 Jps
17252 GarbageCollectionAnalysisExample
16048
2084 Main

17252 is the vmid which we need.

Now we will learn how to use jmap and jhat

Use jmap - to generate heap dump

From java docs about jmap “jmap prints shared object memory maps or heap memory details of a given process or core file or a remote debug server”

Use following command to generate heap dump >

C:\>jmap -dump:file=E:\heapDump.jmap 17252
Dumping heap to E:\heapDump.jmap ...
Heap dump file created

Where 17252 is the vmid (picked from above).

Heap dump will be generated in E:\heapDump.jmap

Now use Jhat Jhat is used for analyzing the garbage collection dump in java -

C:\>jhat E:\heapDump.jmap
Reading from E:\heapDump.jmap...
Dump file created Mon Nov 07 23:59:19 IST 2016
Snapshot read, resolving...
Resolving 241865 objects...
Chasing references, expect 48 dots................................................
Eliminating duplicate references................................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

By default, it will start http server on port 7000. Then we will go to http://localhost:7000/

Courtesy : JMAP, How to monitor and analyze the garbage collection in 10 ways

Passing arguments to require (when loading module)

Based on your comments in this answer, I do what you're trying to do like this:

module.exports = function (app, db) {
    var module = {};

    module.auth = function (req, res) {
        // This will be available 'outside'.
        // Authy stuff that can be used outside...
    };

    // Other stuff...
    module.pickle = function(cucumber, herbs, vinegar) {
        // This will be available 'outside'.
        // Pickling stuff...
    };

    function jarThemPickles(pickle, jar) {
        // This will be NOT available 'outside'.
        // Pickling stuff...

        return pickleJar;
    };

    return module;
};

I structure pretty much all my modules like that. Seems to work well for me.

Select the first 10 rows - Laravel Eloquent

Another way to do it is using a limit method:

Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:

Listing::inRandomOrder()->limit(10)->get();

How can I measure the actual memory usage of an application or process?

ps -eo size,pid,user,command --sort -size | \
    awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' |\
    cut -d "" -f2 | cut -d "-" -f1

Use this as root and you can get a clear output for memory usage by each process.

OUTPUT EXAMPLE:

     0.00 Mb COMMAND 
  1288.57 Mb /usr/lib/firefox
   821.68 Mb /usr/lib/chromium/chromium 
   762.82 Mb /usr/lib/chromium/chromium 
   588.36 Mb /usr/sbin/mysqld 
   547.55 Mb /usr/lib/chromium/chromium 
   523.92 Mb /usr/lib/tracker/tracker
   476.59 Mb /usr/lib/chromium/chromium 
   446.41 Mb /usr/bin/gnome
   421.62 Mb /usr/sbin/libvirtd 
   405.11 Mb /usr/lib/chromium/chromium 
   302.60 Mb /usr/lib/chromium/chromium 
   291.46 Mb /usr/lib/chromium/chromium 
   284.56 Mb /usr/lib/chromium/chromium 
   238.93 Mb /usr/lib/tracker/tracker
   223.21 Mb /usr/lib/chromium/chromium 
   197.99 Mb /usr/lib/chromium/chromium 
   194.07 Mb conky 
   191.92 Mb /usr/lib/chromium/chromium 
   190.72 Mb /usr/bin/mongod 
   169.06 Mb /usr/lib/chromium/chromium 
   155.11 Mb /usr/bin/gnome
   136.02 Mb /usr/lib/chromium/chromium 
   125.98 Mb /usr/lib/chromium/chromium 
   103.98 Mb /usr/lib/chromium/chromium 
    93.22 Mb /usr/lib/tracker/tracker
    89.21 Mb /usr/lib/gnome
    80.61 Mb /usr/bin/gnome
    77.73 Mb /usr/lib/evolution/evolution
    76.09 Mb /usr/lib/evolution/evolution
    72.21 Mb /usr/lib/gnome
    69.40 Mb /usr/lib/evolution/evolution
    68.84 Mb nautilus
    68.08 Mb zeitgeist
    60.97 Mb /usr/lib/tracker/tracker
    59.65 Mb /usr/lib/evolution/evolution
    57.68 Mb apt
    55.23 Mb /usr/lib/gnome
    53.61 Mb /usr/lib/evolution/evolution
    53.07 Mb /usr/lib/gnome
    52.83 Mb /usr/lib/gnome
    51.02 Mb /usr/lib/udisks2/udisksd 
    50.77 Mb /usr/lib/evolution/evolution
    50.53 Mb /usr/lib/gnome
    50.45 Mb /usr/lib/gvfs/gvfs
    50.36 Mb /usr/lib/packagekit/packagekitd 
    50.14 Mb /usr/lib/gvfs/gvfs
    48.95 Mb /usr/bin/Xwayland :1024 
    46.21 Mb /usr/bin/gnome
    42.43 Mb /usr/bin/zeitgeist
    42.29 Mb /usr/lib/gnome
    41.97 Mb /usr/lib/gnome
    41.64 Mb /usr/lib/gvfs/gvfsd
    41.63 Mb /usr/lib/gvfs/gvfsd
    41.55 Mb /usr/lib/gvfs/gvfsd
    41.48 Mb /usr/lib/gvfs/gvfsd
    39.87 Mb /usr/bin/python /usr/bin/chrome
    37.45 Mb /usr/lib/xorg/Xorg vt2 
    36.62 Mb /usr/sbin/NetworkManager 
    35.63 Mb /usr/lib/caribou/caribou 
    34.79 Mb /usr/lib/tracker/tracker
    33.88 Mb /usr/sbin/ModemManager 
    33.77 Mb /usr/lib/gnome
    33.61 Mb /usr/lib/upower/upowerd 
    33.53 Mb /usr/sbin/gdm3 
    33.37 Mb /usr/lib/gvfs/gvfsd
    33.36 Mb /usr/lib/gvfs/gvfs
    33.23 Mb /usr/lib/gvfs/gvfs
    33.15 Mb /usr/lib/at
    33.15 Mb /usr/lib/at
    30.03 Mb /usr/lib/colord/colord 
    29.62 Mb /usr/lib/apt/methods/https 
    28.06 Mb /usr/lib/zeitgeist/zeitgeist
    27.29 Mb /usr/lib/policykit
    25.55 Mb /usr/lib/gvfs/gvfs
    25.55 Mb /usr/lib/gvfs/gvfs
    25.23 Mb /usr/lib/accountsservice/accounts
    25.18 Mb /usr/lib/gvfs/gvfsd 
    25.15 Mb /usr/lib/gvfs/gvfs
    25.15 Mb /usr/lib/gvfs/gvfs
    25.12 Mb /usr/lib/gvfs/gvfs
    25.10 Mb /usr/lib/gnome
    25.10 Mb /usr/lib/gnome
    25.07 Mb /usr/lib/gvfs/gvfsd 
    24.99 Mb /usr/lib/gvfs/gvfs
    23.26 Mb /usr/lib/chromium/chromium 
    22.09 Mb /usr/bin/pulseaudio 
    19.01 Mb /usr/bin/pulseaudio 
    18.62 Mb (sd
    18.46 Mb (sd
    18.30 Mb /sbin/init 
    18.17 Mb /usr/sbin/rsyslogd 
    17.50 Mb gdm
    17.42 Mb gdm
    17.09 Mb /usr/lib/dconf/dconf
    17.09 Mb /usr/lib/at
    17.06 Mb /usr/lib/gvfs/gvfsd
    16.98 Mb /usr/lib/at
    16.91 Mb /usr/lib/gdm3/gdm
    16.86 Mb /usr/lib/gvfs/gvfsd
    16.86 Mb /usr/lib/gdm3/gdm
    16.85 Mb /usr/lib/dconf/dconf
    16.85 Mb /usr/lib/dconf/dconf
    16.73 Mb /usr/lib/rtkit/rtkit
    16.69 Mb /lib/systemd/systemd
    13.13 Mb /usr/lib/chromium/chromium 
    13.13 Mb /usr/lib/chromium/chromium 
    10.92 Mb anydesk 
     8.54 Mb /sbin/lvmetad 
     7.43 Mb /usr/sbin/apache2 
     6.82 Mb /usr/sbin/apache2 
     6.77 Mb /usr/sbin/apache2 
     6.73 Mb /usr/sbin/apache2 
     6.66 Mb /usr/sbin/apache2 
     6.64 Mb /usr/sbin/apache2 
     6.63 Mb /usr/sbin/apache2 
     6.62 Mb /usr/sbin/apache2 
     6.51 Mb /usr/sbin/apache2 
     6.25 Mb /usr/sbin/apache2 
     6.22 Mb /usr/sbin/apache2 
     3.92 Mb bash 
     3.14 Mb bash 
     2.97 Mb bash 
     2.95 Mb bash 
     2.93 Mb bash 
     2.91 Mb bash 
     2.86 Mb bash 
     2.86 Mb bash 
     2.86 Mb bash 
     2.84 Mb bash 
     2.84 Mb bash 
     2.45 Mb /lib/systemd/systemd
     2.30 Mb (sd
     2.28 Mb /usr/bin/dbus
     1.84 Mb /usr/bin/dbus
     1.46 Mb ps 
     1.21 Mb openvpn hackthebox.ovpn 
     1.16 Mb /sbin/dhclient 
     1.16 Mb /sbin/dhclient 
     1.09 Mb /lib/systemd/systemd 
     0.98 Mb /sbin/mount.ntfs /dev/sda3 /media/n0bit4/Data 
     0.97 Mb /lib/systemd/systemd 
     0.96 Mb /lib/systemd/systemd 
     0.89 Mb /usr/sbin/smartd 
     0.77 Mb /usr/bin/dbus
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.74 Mb /usr/bin/dbus
     0.71 Mb /usr/lib/apt/methods/http 
     0.68 Mb /bin/bash /usr/bin/mysqld_safe 
     0.68 Mb /sbin/wpa_supplicant 
     0.66 Mb /usr/bin/dbus
     0.61 Mb /lib/systemd/systemd
     0.54 Mb /usr/bin/dbus
     0.46 Mb /usr/sbin/cron 
     0.45 Mb /usr/sbin/irqbalance 
     0.43 Mb logger 
     0.41 Mb awk { hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" } 
     0.40 Mb /usr/bin/ssh
     0.34 Mb /usr/lib/chromium/chrome
     0.32 Mb cut 
     0.32 Mb cut 
     0.00 Mb [kthreadd] 
     0.00 Mb [ksoftirqd/0] 
     0.00 Mb [kworker/0:0H] 
     0.00 Mb [rcu_sched] 
     0.00 Mb [rcu_bh] 
     0.00 Mb [migration/0] 
     0.00 Mb [lru
     0.00 Mb [watchdog/0] 
     0.00 Mb [cpuhp/0] 
     0.00 Mb [cpuhp/1] 
     0.00 Mb [watchdog/1] 
     0.00 Mb [migration/1] 
     0.00 Mb [ksoftirqd/1] 
     0.00 Mb [kworker/1:0H] 
     0.00 Mb [cpuhp/2] 
     0.00 Mb [watchdog/2] 
     0.00 Mb [migration/2] 
     0.00 Mb [ksoftirqd/2] 
     0.00 Mb [kworker/2:0H] 
     0.00 Mb [cpuhp/3] 
     0.00 Mb [watchdog/3] 
     0.00 Mb [migration/3] 
     0.00 Mb [ksoftirqd/3] 
     0.00 Mb [kworker/3:0H] 
     0.00 Mb [kdevtmpfs] 
     0.00 Mb [netns] 
     0.00 Mb [khungtaskd] 
     0.00 Mb [oom_reaper] 
     0.00 Mb [writeback] 
     0.00 Mb [kcompactd0] 
     0.00 Mb [ksmd] 
     0.00 Mb [khugepaged] 
     0.00 Mb [crypto] 
     0.00 Mb [kintegrityd] 
     0.00 Mb [bioset] 
     0.00 Mb [kblockd] 
     0.00 Mb [devfreq_wq] 
     0.00 Mb [watchdogd] 
     0.00 Mb [kswapd0] 
     0.00 Mb [vmstat] 
     0.00 Mb [kthrotld] 
     0.00 Mb [ipv6_addrconf] 
     0.00 Mb [acpi_thermal_pm] 
     0.00 Mb [ata_sff] 
     0.00 Mb [scsi_eh_0] 
     0.00 Mb [scsi_tmf_0] 
     0.00 Mb [scsi_eh_1] 
     0.00 Mb [scsi_tmf_1] 
     0.00 Mb [scsi_eh_2] 
     0.00 Mb [scsi_tmf_2] 
     0.00 Mb [scsi_eh_3] 
     0.00 Mb [scsi_tmf_3] 
     0.00 Mb [scsi_eh_4] 
     0.00 Mb [scsi_tmf_4] 
     0.00 Mb [scsi_eh_5] 
     0.00 Mb [scsi_tmf_5] 
     0.00 Mb [bioset] 
     0.00 Mb [kworker/1:1H] 
     0.00 Mb [kworker/3:1H] 
     0.00 Mb [kworker/0:1H] 
     0.00 Mb [kdmflush] 
     0.00 Mb [bioset] 
     0.00 Mb [kdmflush] 
     0.00 Mb [bioset] 
     0.00 Mb [jbd2/sda5
     0.00 Mb [ext4
     0.00 Mb [kworker/2:1H] 
     0.00 Mb [kauditd] 
     0.00 Mb [bioset] 
     0.00 Mb [drbd
     0.00 Mb [irq/27
     0.00 Mb [i915/signal:0] 
     0.00 Mb [i915/signal:1] 
     0.00 Mb [i915/signal:2] 
     0.00 Mb [ttm_swap] 
     0.00 Mb [cfg80211] 
     0.00 Mb [kworker/u17:0] 
     0.00 Mb [hci0] 
     0.00 Mb [hci0] 
     0.00 Mb [kworker/u17:1] 
     0.00 Mb [iprt
     0.00 Mb [iprt
     0.00 Mb [kworker/1:0] 
     0.00 Mb [kworker/3:0] 
     0.00 Mb [kworker/0:0] 
     0.00 Mb [kworker/2:0] 
     0.00 Mb [kworker/u16:0] 
     0.00 Mb [kworker/u16:2] 
     0.00 Mb [kworker/3:2] 
     0.00 Mb [kworker/2:1] 
     0.00 Mb [kworker/1:2] 
     0.00 Mb [kworker/0:2] 
     0.00 Mb [kworker/2:2] 
     0.00 Mb [kworker/0:1] 
     0.00 Mb [scsi_eh_6] 
     0.00 Mb [scsi_tmf_6] 
     0.00 Mb [usb
     0.00 Mb [bioset] 
     0.00 Mb [kworker/3:1] 
     0.00 Mb [kworker/u16:1] 

How can I see an the output of my C programs using Dev-C++?

You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.

Best way to store passwords in MYSQL database

Passwords in the database should be stored encrypted. One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt DELETED: MD5 or SHA1. (those are older, vulnerable

In addition to that you can use additional per-user generated random string - 'salt':

$salt = MD5($this->createSalt());

$Password = SHA2($postData['Password'] . $salt);

createSalt() in this case is a function that generates a string from random characters.

EDIT: or if you want more security, you can even add 2 salts: $salt1 . $pass . $salt2

Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say). It should minimize success of brute force attacks.

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

How do I check in JavaScript if a value exists at a certain array index?

if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}

Show current assembly instruction in GDB

From within gdb press Ctrl x 2 and the screen will split into 3 parts.

First part will show you the normal code in high level language.

Second will show you the assembly equivalent and corresponding instruction Pointer.

Third will present you the normal gdb prompt to enter commands.

See the screen shot

Invalid URI: The format of the URI could not be determined

Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx

EDIT:

You need to put the protocol prefix in front the address, i.e. in your case "ftp://"

CodeIgniter htaccess and URL rewrite issues

For those users of wamp server, follow the first 2 steps of @Raul Chipad's solution then:

  1. Click the wamp icon (normally in green), go to "Apache" > "Apache modules" > "rewrite_module". The "rewrite_module" should be ticked! And then it's the way to go!

Check if value exists in the array (AngularJS)

U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {
                arr.splice(arr.pop(item));

            } });

        submitFields.push({"field":field,"value":value});
    };

How to set Spring profile from system variable?

SPRING_PROFILES_ACTIVE is the environment variable to override/pick Spring profile

Spring: @Component versus @Bean

Both approaches aim to register target type in Spring container.

The difference is that @Bean is applicable to methods, whereas @Component is applicable to types.

Therefore when you use @Bean annotation you control instance creation logic in method's body (see example above). With @Component annotation you cannot.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

plt.cla() means clear current axis

plt.clf() means clear current figure

also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)

Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

How to load an ImageView by URL in Android?

I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.

InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");

What is hashCode used for? Is it unique?

It's not unique to WP7--it's present on all .Net objects. It sort of does what you describe, but I would not recommend it as a unique identifier in your apps, as it is not guaranteed to be unique.

Object.GetHashCode Method

Iterating over every property of an object in javascript using Prototype?

There's no need for Prototype here: JavaScript has for..in loops. If you're not sure that no one messed with Object.prototype, check hasOwnProperty() as well, ie

for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        doSomethingWith(obj[prop]);
}

Let JSON object accept bytes or let urlopen output strings

I have come to opinion that the question is the best answer :)

import json
from urllib.request import urlopen

response = urlopen("site.com/api/foo/bar").read().decode('utf8')
obj = json.loads(response)

Laravel csrf token mismatch for ajax POST Request

If you are using template files, than you can put your meta tag in the head section (or whatever you name it) which contain your meta tags.

@section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@endsection

Next thing, you need to put the headers attribute to your ajax(in my example, I am using datatable with server-side processing:

"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}

Here is the full datatable ajax example:

$('#datatable_users').DataTable({
        "responsive": true,
        "serverSide": true,
        "processing": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": {
            "type": "POST",
            "headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
            "url": "/getUsers",
            "dataType": "json",
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) {
                console.log(data);
            },
            "complete": function(response) {
                console.log(response);
           }
        }
    });

After doing this, you should get 200 status for your ajax request.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

Why is my CSS bundling not working with a bin deployed MVC4 app?

With Visual Studio 2015 I found the problem was caused by referencing the .min version of a javascript file in the BundleConfig when debug=true is set in the web.config.

For example, with jquery specifying the following in BundleConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.min.js"));

resulted in the jquery not loading correctly at all when debug=true was set in the web.config.

Referencing the un-minified version:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

corrects the problem.

Setting debug=false also corrects the problem, but of course that is not exactly helpful.

It is also worth noting that while some minified javascript files loaded correctly and others did not. I ended up removing all minified javascript files in favor of VS handling minification for me.

Write to Windows Application Event Log

try

   System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
   appLog.Source = "This Application's Name";
   appLog.WriteEntry("An entry to the Application event log.");

how do I use an enum value on a switch statement in C++

Some things to note:

You should always declare your enum inside a namespace as enums are not proper namespaces and you will be tempted to use them like one.

Always have a break at the end of each switch clause execution will continue downwards to the end otherwise.

Always include the default: case in your switch.

Use variables of enum type to hold enum values for clarity.

see here for a discussion of the correct use of enums in C++.

This is what you want to do.

namespace choices
{
    enum myChoice 
    { 
        EASY = 1 ,
        MEDIUM = 2, 
        HARD = 3  
    };
}

int main(int c, char** argv)
{
    choices::myChoice enumVar;
    cin >> enumVar;
    switch (enumVar)
    {
        case choices::EASY:
        {
            // do stuff
            break;
        }
        case choices::MEDIUM:
        {
            // do stuff
            break;
        }

        default:
        {
            // is likely to be an error
        }
    };

}

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

Swing vs JavaFx for desktop applications

As stated by Oracle, JavaFX is the next step in their Java based rich client strategy. Accordingly, this is what I recommend for your situation:

What would be easier and cleaner to maintain

  • JavaFX has introduced several improvements over Swing, such as, possibility to markup UIs with FXML, and theming with CSS. It has great potential to write a modular, clean & maintainable code.

What would be faster to build from scratch

  • This is highly dependent on your skills and the tools you use.
    • For swing, various IDEs offer tools for rapid development. The best I personally found is the GUI builder in NetBeans.
    • JavaFX has support from various IDEs as well, though not as mature as the support Swing has at the moment. However, its support for markup in FXML & CSS make GUI development on JavaFX intuitive.

MVC Pattern Support

  • JavaFX is very friendly with MVC pattern, and you can cleanly separate your work as: presentation (FXML, CSS), models(Java, domain objects) and logic(Java).
  • IMHO, the MVC support in Swing isn't very appealing. The flow you'll see across various components lacks consistency.

For more info, please take a look these FAQ post by Oracle regarding JavaFX here.

How to connect to LocalDB in Visual Studio Server Explorer?

I followed the steps above, but I forgot to install the SQL Server 2014 LocalDB before the Visual Studio 2015 configuration.

My steps are as follow:

  1. Install the SQL Server 2014 LocalDB;
  2. Open Visual Studio 2015 and then SQL Server Object Explorer;
  3. Find your LocalDB under the SQL Server tag.

Hope this help anybody.

How do I add comments to package.json for npm install?

My take on the frustration of no comments in JSON. I create new nodes, named for the nodes they refer to, but prefixed with underscores. This is imperfect, but functional.

{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "__start": [
        "a note about how the start script works"
    ],
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "__proxy": [
    "A note about how proxy works",
    "multilines are easy enough to add"
  ],
  "proxy": "http://server.whatever.com:8000"
}

Xcode process launch failed: Security

"If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you really want to run it. Say “yes” and then Build & Run again."

To add to that, this only holds true the moment you get the error, if you click OK, then tap on the app. It will do nothing. Scratched my head on that for 30 odd minutes, searching for alternative ways to address the problem.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Must be used convert, not cast:

SELECT
 CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
 COLLATE Cyrillic_General_CI_AI

(http://blog.sqlpositive.com/2010/03/using-convert-with-collate-to-strip-accents-from-unicode-strings/)

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

How do I show multiple recaptchas on a single page?

The grecaptcha.getResponse() method accepts an optional "widget_id" parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created, it is not related to the attribute id of the reCAPTCHA container!!

Each reCAPTCHA has its own response data. You have to give the reCAPTCHA div an ID and pass it to the getResponse method:

e.g.

<div id="reCaptchaLogin"
     class="g-recaptcha required-entry"
     data-sitekey="<?php echo $this->helper('recaptcha')->getKey(); ?>"
     data-theme="<?php echo($this->helper('recaptcha')->getTheme()); ?>"
     style="transform:scale(0.82);-webkit-transform:scale(0.82);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>


<script type="text/javascript">
  var CaptchaCallback = function() {
    jQuery('.g-recaptcha').each(function(index, el) {
        grecaptcha.render(el, {
            'sitekey' : jQuery(el).attr('data-sitekey')
            ,'theme' : jQuery(el).attr('data-theme')
            ,'size' : jQuery(el).attr('data-size')
            ,'tabindex' : jQuery(el).attr('data-tabindex')
            ,'callback' : jQuery(el).attr('data-callback')
            ,'expired-callback' : jQuery(el).attr('data-expired-callback')
            ,'error-callback' : jQuery(el).attr('data-error-callback')
        });
    });
  };
</script>

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

Access response:

var reCaptchaResponse = grecaptcha.getResponse(0);

or

var reCaptchaResponse = grecaptcha.getResponse(1);

Filter an array using a formula (without VBA)

Sounds like you're just trying to do a classic two-column lookup. http://www.dailydoseofexcel.com/archives/2009/04/21/vlookup-on-two-columns/

Tons of solutions for this, most simple is probably the following (which doesn't require an array formula):

=SUMPRODUCT((Lookup!A:A=Param!A1)*(Lookup!B:B=Param!B1)*(Lookup!C:C))

To translate your specific example, you would use:

=SUMPRODUCT((A1:A3=A2)*(B1:B3="B")*(C1:C3))

MySQL Data Source not appearing in Visual Studio

i install mysql for visual studio and the problem simply solved.although version of my visual studio is 2012!

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

How can I dismiss the on screen keyboard?

To summarize, this is a working solution for Flutter 1.17:

Wrap your Widget like this:

GestureDetector(
        onTap: FocusScope.of(context).unfocus,
        child: YourWidget(),
);

Ignoring SSL certificate in Apache HttpClient 4.3

Trust All Certs in Apache HTTP Client

TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                        }
                        public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                        }
                    }
                };

          try {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sc);
                httpclient = HttpClients.custom().setSSLSocketFactory(
                        sslsf).build();
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

No Multiline Lambda in Python: Why not?

I was just playing a bit to try to make a dict comprehension with reduce, and come up with this one liner hack:

In [1]: from functools import reduce
In [2]: reduce(lambda d, i: (i[0] < 7 and d.__setitem__(*i[::-1]), d)[-1], [{}, *{1:2, 3:4, 5:6, 7:8}.items()])                                                                                                                                                                 
Out[3]: {2: 1, 4: 3, 6: 5}

I was just trying to do the same as what was done in this Javascript dict comprehension: https://stackoverflow.com/a/11068265

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

For me, the problem that caused this error arose when I was saving a new row to the database, but a field was null. In the database table design, that field is NOT NULL. So when I tried to save a new row with a null value for not-null field, Visual Studio threw this error. Thus, I made sure that the field was assigned a value, and the problem was fixed.

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Download the version of Connector from https://dev.mysql.com/downloads/connector/c/6.0.html For my case I had installed 64 bit of connector and my python was 32 bit. So I had to copy MySQL from program files to Program Files(86)

Android ListView selected item stay highlighted

Use the id instead:

This is the easiest method that can handle even if the list is long:

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;
    rowView = inflater.inflate(R.layout.list_item, null);
    //Handle your items.
    //StringHolder.mSelectedItem is a public static variable.
    if(getItemId(position)==StringHolder.mSelectedItem){
        rowView.setBackgroundColor(Color.LTGRAY);

    }else{
        rowView.setBackgroundColor(Color.TRANSPARENT);
    }
    return rowView;
}

And then in your onclicklistener:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
            catagoryAdapter.notifyDataSetChanged();
.....

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

JavaScript check if variable exists (is defined/initialized)

It depends if you just care that the variable has been defined or if you want it to have a meaningful value.

Checking if the type is undefined will check if the variable has been defined yet.

=== null or !== null will only check if the value of the variable is exactly null.

== null or != null will check if the value is undefined or null.

if(value) will check if the variable is undefined, null, 0, or an empty string.

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

IIS7 Permissions Overview - ApplicationPoolIdentity

Part A: Configuring your Application Pool

Suppose the Application Pool is named 'MyPool' Go to 'Advanced Settings' of the Application Pool from the IIS Manager

  1. Scroll down to 'Identity'. Trying to edit the value will bring up a dialog box. Select 'Built-In account' and under it, select 'ApplicationPoolIdentity'.

  2. A few lines below 'Identity', you should find 'Load User Profile'. This value should be set to 'True'.

Part B: Configuring your website

  1. Website Name: SiteName (just an example)
  2. Physical Path: C:\Whatever (just an example)
  3. Connect as... : Application User (pass-through authentication) (The above settings can be found in 'Basic Settings' of the site in the IIS Manager)
  4. After configuring the basic settings, look for the 'Authentication' configuration under 'IIS' in the main console of the site. Open it. You should see an option for 'Anonymous Authentication'. Make sure it is enabled. Then right click and 'Edit...' it. Select 'Application Pool Identity'.

Part C: Configuring your folder

The folder in question is C:\Whatever

  1. Go to Properties - Sharing - Advanced Sharing - Permissions, and tick 'Share this folder'
  2. In the same dialog box, you will find a button 'Permissions'. Click it.
  3. A new dialog box will open. Click 'Add'.
  4. A new dialog box 'Select Users or Groups' will open. Under 'From this location' make sure the name is the same as your local host computer. Then, under 'Enter the object names', type 'IIS AppPool\MyPool' and click 'Check Names' and then 'Ok'
  5. Give full sharing permissions for 'MyPool' user. Apply it and close the folder properties
  6. Open folder properties again. This time, go to Security - Advanced - Permission, and click Add. There will be an option 'Select a Principal' at the top, or some other option to choose a user. Click it.
  7. The 'Select Users or Groups' dialog box will open again. Repeat step 4.
  8. Give all or as many permissions you need to the 'MyPool' user.
  9. Check 'Replace all child object permissions..." and Apply and close.

You should now be able to use the browse the website

Adding n hours to a date in Java?

Something like:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() + 
                        (2L * hoursInMillis)); // Adds 2 hours

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

PHP Unset Session Variable

I am including this answer in case someone comes to this page for the same reason I did. I just wasted an embarrassing amount of time trying to track the problem down. I was calling:

unset($_SESSION['myVar']);

from a logout script. Then navigating to a page that required login, and the server still thought I was logged in. The problem was that the logout script was not calling:

session_start();

Unsetting a session var DOES NOT WORK unless you start the session first.

Axios having CORS issue

CORS issue can be simply resolved by following this:

Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

TextView Marquee not working

android:singleLine="true"
android:ellipsize="marquee"

are the only required attributes and scrolling even works with layout_weight defined with layout_width=0dp

here is some sample code:

<TextView 
            android:id="@+id/scroller"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#FFFFFF"
            android:text="Some veryyyyy long text with all the characters that cannot fit in screen, it so sad :( that I will not scroll"
            android:layout_marginLeft="4dp"
            android:layout_weight="3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            />

But what is most important is implicitely or explicitely TextView should get selected.

You can do this with:

TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);

Remove json element

All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:

var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];

This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.

What is dynamic programming?

Dynamic programming is a technique for solving problems with overlapping sub problems. A dynamic programming algorithm solves every sub problem just once and then Saves its answer in a table (array). Avoiding the work of re-computing the answer every time the sub problem is encountered. The underlying idea of dynamic programming is: Avoid calculating the same stuff twice, usually by keeping a table of known results of sub problems.

The seven steps in the development of a dynamic programming algorithm are as follows:

  1. Establish a recursive property that gives the solution to an instance of the problem.
  2. Develop a recursive algorithm as per recursive property
  3. See if same instance of the problem is being solved again an again in recursive calls
  4. Develop a memoized recursive algorithm
  5. See the pattern in storing the data in the memory
  6. Convert the memoized recursive algorithm into iterative algorithm
  7. Optimize the iterative algorithm by using the storage as required (storage optimization)

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

Make sure the newest Framework (the one you compiled your app with) is first in the PATH. That solved the problem for me. (Found on a forum)

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

How do I set bold and italic on UILabel of iPhone/iPad?

 btn.titleLabel.font=[UIFont fontWithName:@"Helvetica neue" size:10];
 btn.titleLabel.font =  [UIFont boldSystemFontOfSize:btnPrev.titleLabel.font.pointSize+3];

you can do bold label/button font also using this

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

RecyclerView - Get view at particular position

You can make ArrayList of ViewHolder :

 ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
 ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();

and, all store ViewHolder(s) in the list like :

 @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        final String str = arrayList.get(position);

        myViewHolders.add(position,holder);
}

and add/remove other ViewHolder in the ArrayList as per your requirement.

How to add System.Windows.Interactivity to project?

If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0 (the NuGet .dll wont work) that you can find under :

PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll

Just add this .dll manually as Reference and it should be fine.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

Schema::table is to modify an existing table, use Schema::create to create new.

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

jQuery AJAX submit form

I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input"); 
let formData = new FormData(); 
for (let input of formInputs) {
    formData.append(input.name, input.value); 
}

fetch(form.action,
    {
        method: form.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

How can I check file size in Python?

The other answers work for real files, but if you need something that works for "file-like objects", try this:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().

Edit

Another difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.

Edit 2

At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

try this one

    <dependency>
        <groupId>com.hynnet</groupId>
        <artifactId>oracle-driver-ojdbc6</artifactId>
        <version>12.1.0.1</version>
    </dependency>

Make a nav bar stick

You can do it with CSS only by creating your menu twice. It's not ideal but it gives you the opportunity have a different design for the menu once it's on top and you'll have nothing else than CSS, no jquery. Here is an example with DIV (you can of course change it to NAV if you prefer):

<div id="hiddenmenu">
 THIS IS MY HIDDEN MENU
</div>
<div id="header">
 Here is my header with a lot of text and my main menu
</div>
<div id="body">
 MY BODY
</div>

And then have the following CSS:

#hiddenmenu {
position: fixed;
top: 0;
z-index:1;
 }
#header {
top: 0;
position:absolute;
z-index:2;
 }
#body {
padding-top: 80px;
position:absolute;
z-index: auto;
 }

Here is a fiddle for you to see: https://jsfiddle.net/brghtk4z/1/

std::cin input with spaces?

The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:

std::string s;
std::getline(std::cin >> std::ws, s);

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

What is the easiest way to ignore a JPA field during persistence?

use @Transient to make JPA ignoring the field.

but! Jackson will not serialize that field as well. to solve just add @JsonProperty

an example

@Transient
@JsonProperty
private boolean locked;

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

Evaluating string "3*(4+2)" yield int 18

You could fairly easily run this through the CSharpCodeProvider with suitable fluff wrapping it (a type and a method, basically). Likewise you could go through VB etc - or JavaScript, as another answer has suggested. I don't know of anything else built into the framework at this point.

I'd expect that .NET 4.0 with its support for dynamic languages may well have better capabilities on this front.

Viewing localhost website from mobile device

To view localhost website from mobile device you have to follow thoses steps :

  • In your computer, you have to retrieve your IP address (Run > cmd > ipconfig)
  • If your localhost use a specific port (like localhost:12345 ), you have to open the port on your computer (Control Panel > System and Security > Firewall > Advanced settings and add Inbound rule)
  • Finally, you can access to your website from mobile device by navigate to : http://192.168.X.X:12345/

Hope it helps

Laravel Check If Related Model Exists

You can use the relationLoaded method on the model object. This saved my bacon so hopefully it helps someone else. I was given this suggestion when I asked the same question on Laracasts.

Elegant way to check for missing packages and install them?

source("https://bioconductor.org/biocLite.R")
if (!require("ggsci")) biocLite("ggsci")

SQL Server AS statement aliased column within WHERE statement

Both accepted answer and Logical Processing Order explain why you could not do what you proposed.

Possible solution:

  • use derived table (cte/subquery)
  • use expression in WHERE
  • create view/computed column

From SQL Server 2008 you could use APPLY operator combined with Table valued Constructor:

SELECT *, s.distance
FROM poi_table 
CROSS APPLY (VALUES(6371*1000*acos(cos(radians(42.3936868308))*cos(radians(lat))*cos(radians(lon)-radians(-72.5277256966))+sin(radians(42.3936868308))*sin(radians(lat))))) AS s(distance)
WHERE distance < 500;

LiveDemo

Node.js Mongoose.js string to ObjectId function

I couldn't resolve this method (admittedly I didn't search for long)

mongoose.mongo.BSONPure.ObjectID.fromHexString

If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.

You could use something like this however, which gives a bit more flex:

function toObjectId(ids) {

    if (ids.constructor === Array) {
        return ids.map(mongoose.Types.ObjectId);
    }

    return mongoose.Types.ObjectId(ids);
}

Preferred way of getting the selected item of a JComboBox

Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"

MYSQL query between two timestamps

You just need to convert your dates to UNIX_TIMESTAMP. You can write your query like this:

SELECT *
FROM eventList
WHERE
  date BETWEEN
      UNIX_TIMESTAMP('2013/03/26')
      AND
      UNIX_TIMESTAMP('2013/03/27 23:59:59');

When you don't specify the time, MySQL will assume 00:00:00 as the time for the given date.

jQuery .ready in a dynamically inserted iframe

Basically what others have already posted but IMHO a bit cleaner:

$('<iframe/>', {
    src: 'https://example.com/',
    load: function() {
        alert("loaded")
    }
}).appendTo('body');

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

java.lang.NoClassDefFoundError in junit

The same problem can occur if you have downloaded JUnit jar from the JUnit website, but forgotten to download the Hamcrest jar - both are required (the instructions say to download both, but I skipped ahead! Oops)

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

Undefined symbols for architecture arm64

If you use a .framework/.a writed by c++, where you invoke the c++ code, whice file need change to .mm file.

I losed half a day in that...

Eclipse Java Missing required source folder: 'src'

Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.

good luck!

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back