Programs & Examples On #Protected folders

How to get a enum value from string in C#?

Using Enum.TryParse you don't need the Exception handling:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.

Colouring

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Integer division: How do you produce a double?

use something like:

double step = 1d / 5;

(1d is a cast to double)

How to show a GUI message box from a bash script in linux?

Example bash script for using Gambas GTK/QT Controls(GUI Objects): The Gambas IDE can be used to design even large GUIs and act as a GUI server. Example expplications can be downloaded from the Gambas App store.
https://gambas.one/gambasfarm/?id=823&action=search

enter image description here

Move UIView up when the keyboard appears in iOS

Simple solution without adding observer notification

-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.3]; // if you want to slide up the view

    CGRect rect = self.view.frame;

    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}


-(void)textFieldDidEndEditing:(UITextField *)sender
{
     if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:NO];
        }
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
}

Where

#define kOFFSET_FOR_KEYBOARD 80.0

Is there a way to 'pretty' print MongoDB shell output to a file?

I managed to save result with writeFile() function.

> writeFile("/home/pahan/output.txt", tojson(db.myCollection.find().toArray()))

Mongo shell version was 4.0.9

Multiple ping script in Python

This script:

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(1, 10):
                ip="192.168.0.{0}".format(n)
                result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

will produce something like this output:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

You can capture the output if you replace limbo with subprocess.PIPE and use communicate() on the Popen object:

p=Popen( ... )
output=p.communicate()
result=p.wait()

This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:

The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.

C++11 reverse range-based for-loop

template <typename C>
struct reverse_wrapper {

    C & c_;
    reverse_wrapper(C & c) :  c_(c) {}

    typename C::reverse_iterator begin() {return c_.rbegin();}
    typename C::reverse_iterator end() {return c_.rend(); }
};

template <typename C, size_t N>
struct reverse_wrapper< C[N] >{

    C (&c_)[N];
    reverse_wrapper( C(&c)[N] ) : c_(c) {}

    typename std::reverse_iterator<const C *> begin() { return std::rbegin(c_); }
    typename std::reverse_iterator<const C *> end() { return std::rend(c_); }
};


template <typename C>
reverse_wrapper<C> r_wrap(C & c) {
    return reverse_wrapper<C>(c);
}

eg:

int main(int argc, const char * argv[]) {
    std::vector<int> arr{1, 2, 3, 4, 5};
    int arr1[] = {1, 2, 3, 4, 5};

    for (auto i : r_wrap(arr)) {
        printf("%d ", i);
    }
    printf("\n");

    for (auto i : r_wrap(arr1)) {
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

How to display errors on laravel 4?

I had a problem with the white screen after installing a new laravel instance. I couldn't find anything in the logs because (eventually I found out) that the reason for the white screen was that app/storage wasn't writable.

In order to get an error message on the screen I added the following to the public/index.php

try {
    $app->run();
} catch(\Exception $e) {
    echo "<pre>";
    echo $e;
    echo "</pre>";
}

After that it was easy to solve the problem.

How to copy a collection from one database to another in MongoDB

If RAM is not an issue using insertMany is way faster than forEach loop.

var db1 = connect('<ip_1>:<port_1>/<db_name_1>')
var db2 = connect('<ip_2>:<port_2>/<db_name_2>')

var _list = db1.getCollection('collection_to_copy_from').find({})
db2.collection_to_copy_to.insertMany(_list.toArray())

Oracle 'Partition By' and 'Row_Number' keyword

I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...

select a,b,rn 
  from (select a, b, row_number() over (partition by a,b order by a,b) as rn           
          from table) 
 where rn=1;

What is the size of a pointer?

The size of a pointer is the size required by your system to hold a unique memory address (since a pointer just holds the address it points to)

Check if a string contains an element from a list (of strings)

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

Deep copy of a dict in python

A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:

my_dict={'a':1}

my_copy = {}

my_copy.update( my_dict )

my_dict['a']=2

my_dict['a']
Out[34]: 2

my_copy['a']
Out[35]: 1

The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:

my_dict1={'b':2}

my_dict2={'c':3}

my_dict3={ 'b': my_dict1, 'c':my_dict2 }

my_copy = {}

my_copy.update( my_dict3 )

my_dict1['b']='z'

my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}

By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:

import copy

my_copy2 = copy.deepcopy( my_dict3 )

my_dict1['b']='99'

my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}

Java Returning method which returns arraylist?

1. If that class from which you want to call this method, is in the same package, then create an instance of this class and call the method.

2. Use Composition

3. It would be better to have a Generic ArrayList like ArrayList<Integer> etc...

eg:

public class Test{

public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
 }
}


public class T{


public static void main(String[] args){

   Test t = new Test();
   ArrayList<Integer> arr = t.myNumbers();        // You can catch the returned integer arraylist into an arraylist.
 }


}

How to get JSON from URL in JavaScript?

_x000D_
_x000D_
async function fetchDataAsync() {_x000D_
    const response = await fetch('paste URL');_x000D_
    console.log(await response.json())_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
fetchDataAsync();
_x000D_
_x000D_
_x000D_

ImportError: No module named 'Queue'

Queue is in the multiprocessing module so:

from multiprocessing import Queue

When to use reinterpret_cast?

The short answer: If you don't know what reinterpret_cast stands for, don't use it. If you will need it in the future, you will know.

Full answer:

Let's consider basic number types.

When you convert for example int(12) to unsigned float (12.0f) your processor needs to invoke some calculations as both numbers has different bit representation. This is what static_cast stands for.

On the other hand, when you call reinterpret_cast the CPU does not invoke any calculations. It just treats a set of bits in the memory like if it had another type. So when you convert int* to float* with this keyword, the new value (after pointer dereferecing) has nothing to do with the old value in mathematical meaning.

Example: It is true that reinterpret_cast is not portable because of one reason - byte order (endianness). But this is often surprisingly the best reason to use it. Let's imagine the example: you have to read binary 32bit number from file, and you know it is big endian. Your code has to be generic and works properly on big endian (e.g. some ARM) and little endian (e.g. x86) systems. So you have to check the byte order. It is well-known on compile time so you can write constexpr function: You can write a function to achieve this:

/*constexpr*/ bool is_little_endian() {
  std::uint16_t x=0x0001;
  auto p = reinterpret_cast<std::uint8_t*>(&x);
  return *p != 0;
}

Explanation: the binary representation of x in memory could be 0000'0000'0000'0001 (big) or 0000'0001'0000'0000 (little endian). After reinterpret-casting the byte under p pointer could be respectively 0000'0000 or 0000'0001. If you use static-casting, it will always be 0000'0001, no matter what endianness is being used.

EDIT:

In the first version I made example function is_little_endian to be constexpr. It compiles fine on the newest gcc (8.3.0) but the standard says it is illegal. The clang compiler refuses to compile it (which is correct).

How to set image to UIImage

There is an error on this line:

[img setImage:[UIImage imageNamed@"anyImageName"]]; 

It should be:

[img setImage:[UIImage imageNamed:@"anyImageName"]]; 

How to find a value in an array and remove it by using PHP array functions?

<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

Bootstrap 4 align navbar items to the right

For those who is still struggling with this issue in BS4 simply try below code -

<ul class="navbar-nav ml-auto">

vertical-align with Bootstrap 3

Following the accepted answer, if you do not wish to customize the markup, for separation of concerns or simply because you use a CMS, the following solution works fine:

_x000D_
_x000D_
.valign {_x000D_
  font-size: 0;_x000D_
}_x000D_
_x000D_
.valign > [class*="col"] {_x000D_
  display: inline-block;_x000D_
  float: none;_x000D_
  font-size: 14px;_x000D_
  font-size: 1rem;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row valign">_x000D_
   <div class="col-xs-5">_x000D_
      <div style="height:5em;border:1px solid #000">Big</div>_x000D_
   </div>_x000D_
   <div class="col-xs-5">_x000D_
       <div style="height:3em;border:1px solid #F00">Small</div>_x000D_
   </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

The limitation here is that you cannot inherit font size from the parent element because the row sets the font size to 0 in order to remove white space.

Pointer to class data member "::*"

I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.

How to use global variable in node.js?

I would suggest everytime when using global check if the variable is already define by simply check

if (!global.logger){
  global.logger = require('my_logger');
}

I've found it to have better performance

How can I discover the "path" of an embedded resource?

The name of the resource is the name space plus the "pseudo" name space of the path to the file. The "pseudo" name space is made by the sub folder structure using \ (backslashes) instead of . (dots).

public static Stream GetResourceFileStream(String nameSpace, String filePath)
{
    String pseduoName = filePath.Replace('\\', '.');
    Assembly assembly = Assembly.GetExecutingAssembly();
    return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName);
}

The following call:

GetResourceFileStream("my.namespace", "resources\\xml\\my.xml")

will return the stream of my.xml located in the folder-structure resources\xml in the name space: my.namespace.

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Some code examples for simple GET request. Maybe this helps understanding the difference. Using then:

$http.get('/someURL').then(function(response) {
    var data = response.data,
        status = response.status,
        header = response.header,
        config = response.config;
    // success handler
}, function(response) {
    var data = response.data,
        status = response.status,
        header = response.header,
        config = response.config;
    // error handler
});

Using success/error:

$http.get('/someURL').success(function(data, status, header, config) {
    // success handler
}).error(function(data, status, header, config) {
    // error handler
});

Why is setState in reactjs Async instead of Sync?

1) setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.


2) Why would they make setState async as JS is a single threaded language and this setState is not a WebAPI or server call?

This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.

Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

How to pass data between fragments

From the Fragment documentation:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

So I suggest you have look on the basic fragment training docs in the documentation. They're pretty comprehensive with an example and a walk-through guide.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

Sass - Converting Hex to RGBa for background opacity

you can try this solution, is the best... url(github)

// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8

// Extend this class to save bytes
.transparent-background {
  background-color: transparent;
  zoom: 1;
}

// The mixin
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  @extend .transparent-background;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}

// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
  @each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
    .#{$name}-#{$alpha} {
      @include transparent($color, $alpha / 100);
    }
  }
}

// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);

Difference between del, remove, and pop on lists

pop

Takes index (when given, else take last), removes value at that index, and returns value

remove

Takes value, removes first occurrence, and returns nothing

delete

Takes index, removes value at that index, and returns nothing

Fatal error: unexpectedly found nil while unwrapping an Optional values

Almost certainly, your reuse identifier "title" is incorrect.

We can see from the UITableView.h method signature of dequeueReusableCellWithIdentifier that the return type is an Implicitly Unwrapped Optional:

func dequeueReusableCellWithIdentifier(identifier: String!) -> AnyObject! // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.

That's determined by the exclamation mark after AnyObject:

    AnyObject!

So, first thing to consider is, what is an "Implicitly Unwrapped Optional"?

The Swift Programming Language tells us:

Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

So, basically, something that might have been nil at one point, but which from some point on is never nil again. We therefore save ourselves some bother by taking it in as the unwrapped value.

It makes sense in this case for dequeueReusableCellWithIdentifier to return such a value. The supplied identifier must have already been used to register the cell for reuse. Supply an incorrect identifier, the dequeue can't find it, and the runtime returns a nil that should never happen. It's a fatal error, the app crashes, and the Console output gives:

fatal error: unexpectedly found nil while unwrapping an Optional value

Bottom line: check your cell reuse identifier specified in the .storyboard, Xib, or in code, and ensure that it is correct when dequeuing.

C++ where to initialize static const

Only integral values (e.g., static const int ARRAYSIZE) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.

How to get the size of a JavaScript object?

I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.

function roughSizeOfObject( object ) {

    var objectList = [];
    var stack = [ object ];
    var bytes = 0;

    while ( stack.length ) {
        var value = stack.pop();

        if ( typeof value === 'boolean' ) {
            bytes += 4;
        }
        else if ( typeof value === 'string' ) {
            bytes += value.length * 2;
        }
        else if ( typeof value === 'number' ) {
            bytes += 8;
        }
        else if
        (
            typeof value === 'object'
            && objectList.indexOf( value ) === -1
        )
        {
            objectList.push( value );

            for( var i in value ) {
                stack.push( value[ i ] );
            }
        }
    }
    return bytes;
}

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I resolved this by adding @Transactional to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional annotation only applies to methods implemented within a class and not to methods inherited by a class.

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

What is the naming convention in Python for variable and function names?

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"

What is an uber jar?

Über is the German word for above or over (it's actually cognate with the English over).

Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".

The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.

All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.


(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.

How to stop a JavaScript for loop?

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
  if (ele > 3) break;
  console.log(ele);
}

@Cacheable key on multiple method arguments

You can use a Spring-EL expression, for eg on JDK 1.7:

@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

How can I detect the touch event of an UIImageView?

For those of you looking for a Swift 4 solution to this answer, you can use the following to detect a touch event on a UIImageView.

let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true

You will then need to define your selector as follows:

@objc func imageViewTapped() {
    // Image has been tapped
}

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Show tables, describe tables equivalent in redshift

You can simply use the command below to describe a table.

desc table-name

or

desc schema-name.table-name

Convert normal Java Array or ArrayList to Json Array in android

you need external library

 json-lib-2.2.2-jdk15.jar

List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google Gson is the best library http://code.google.com/p/google-gson/

Intercept and override HTTP requests from WebView

It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest().

Reading rows from a CSV file in Python

Use the csv module:

import csv

with open("test.csv", "r") as f:
    reader = csv.reader(f, delimiter="\t")
    for i, line in enumerate(reader):
        print 'line[{}] = {}'.format(i, line)

Output:

line[0] = ['Year:', 'Dec:', 'Jan:']
line[1] = ['1', '50', '60']
line[2] = ['2', '25', '50']
line[3] = ['3', '30', '30']
line[4] = ['4', '40', '20']
line[5] = ['5', '10', '10']

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

This works for me nicely:

mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
  .connect(db) //Connection string defined in another file
  .then(() => console.log("Mongo Connected..."))
  .catch(() => console.log(err));

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

Map and filter an array at the same time

One line reduce with ES6 fancy spread syntax is here!

_x000D_
_x000D_
var options = [_x000D_
  { name: 'One', assigned: true }, _x000D_
  { name: 'Two', assigned: false }, _x000D_
  { name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
const filtered = options_x000D_
  .reduce((result, {name, assigned}) => [...result, ...assigned ? [name] : []], []);_x000D_
_x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

Entity Framework: There is already an open DataReader associated with this Command

I noticed that this error happens when I send an IQueriable to the view and use it in a double foreach, where the inner foreach also needs to use the connection. Simple example (ViewBag.parents can be IQueriable or DbSet):

foreach (var parent in ViewBag.parents)
{
    foreach (var child in parent.childs)
    {

    }
}

The simple solution is to use .ToList() on the collection before using it. Also note that MARS does not work with MySQL.

Use 'import module' or 'from module import'?

Here is another difference not mentioned. This is copied verbatim from http://docs.python.org/2/tutorial/modules.html

Note that when using

from package import item

the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

Contrarily, when using syntax like

import item.subitem.subsubitem

each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

What is the question mark for in a Typescript parameter name

The ? in the parameters is to denote an optional parameter. The Typescript compiler does not require this parameter to be filled in. See the code example below for more details:

// baz: number | undefined means: the second argument baz can be a number or undefined

// = undefined, is default parameter syntax, 
// if the parameter is not filled in it will default to undefined

// Although default JS behaviour is to set every non filled in argument to undefined 
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
    // do stuff
}

// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
    // do stuff
}



fn2('foo', 3); // works
fn2('foo'); // works

fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.


fn1('foo', 3); // works
fn1('foo'); // works

fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

Why doesn't Python have a sign function?

In Python 2, cmp() returns an integer: there's no requirement that the result be -1, 0, or 1, so sign(x) is not the same as cmp(x,0).

In Python 3, cmp() has been removed in favor of rich comparison. For cmp(), Python 3 suggests this:

def cmp(a, b):
    return (a > b) - (a < b)

which is fine for cmp(), but again can't be used for sign() because the comparison operators need not return booleans.

To deal with this possibility, the comparison results must be coerced to booleans:

 def sign(x):
    return bool(x > 0) - bool(x < 0)

This works for any type which is totally ordered (including special values like NaN or infinities).

Checking if a string array contains a value, and if so, getting its position

you can try like this...you can use Array.IndexOf() , if you want to know the position also

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

Create instance of generic type whose constructor requires a parameter?

As Jon pointed out this is life for constraining a non-parameterless constructor. However a different solution is to use a factory pattern. This is easily constrainable

interface IFruitFactory<T> where T : BaseFruit {
  T Create(int weight);
}

public void AddFruit<T>( IFruitFactory<T> factory ) where T: BaseFruit {    
  BaseFruit fruit = factory.Create(weight); /*new Apple(150);*/    
  fruit.Enlist(fruitManager);
}

Yet another option is to use a functional approach. Pass in a factory method.

public void AddFruit<T>(Func<int,T> factoryDel) where T : BaseFruit { 
  BaseFruit fruit = factoryDel(weight); /* new Apple(150); */
  fruit.Enlist(fruitManager);
}

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

This worked for me, you just need to put .html() on the end of - $(response).find("#result")

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Pythonic way to check if a file exists?

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

with open(thepath, 'a'): pass

(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):/else statement blocks are probably more suitable.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

json_encode(): Invalid UTF-8 sequence in argument

The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.

What we have used is to convert these chars to html entities like this:

htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

Why shouldn't I use mysql_* functions in PHP?

There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.

When using mysql_* functions, you have to remember to run user-supplied parameters through mysql_real_escape_string(). If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.

Using prepared statements in PDO or mysqli will make it so that these sorts of programming errors are more difficult to make.

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

or use display property with table-cell;

css

.table-layout {
    display:table;
    width:100%;
}
.table-layout .table-cell {
    display:table-cell;
    border:solid 1px #ccc;
}

.fixed-width-200 {
    width:200px;
}

html

<div class="table-layout">
    <div class="table-cell fixed-width-200">
        <p>fixed width div</p>
    </div>
    <div class="table-cell">
        <p>fluid width div</p>    
    </div>
</div>

http://jsfiddle.net/DnGDz/

Server Error in '/' Application. ASP.NET

  • right-click virtual directory (e.g. MyVirtualDirectory)

  • click convert to application.

Iterate through object properties

Check type

You can check how propt represent object propertis by

typeof propt

to discover that it's just a string (name of property). It come up with every property in the object due the way of how for-in js "build-in" loop works.

_x000D_
_x000D_
var obj = {
    name: "Simon",
    age: "20",
    clothing: {
        style: "simple",
        hipster: false
    }
}

for(var propt in obj){
    console.log(typeof propt,  propt + ': ' + obj[propt]);
}
_x000D_
_x000D_
_x000D_

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

What is the difference between call and apply?

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

Sample code:

_x000D_
_x000D_
function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator
_x000D_
_x000D_
_x000D_

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

How to interpolate variables in strings in JavaScript, without concatenation?

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

Angular 2.0 and Modal Dialog

  • Angular 2 and up
  • Bootstrap css (animation is preserved)
  • NO JQuery
  • NO bootstrap.js
  • Supports custom modal content (just like accepted answer)
  • Recently added support for multiple modals on top of each other.

`

@Component({
  selector: 'app-component',
  template: `
  <button type="button" (click)="modal.show()">test</button>
  <app-modal #modal>
    <div class="app-modal-header">
      header
    </div>
    <div class="app-modal-body">
      Whatever content you like, form fields, anything
    </div>
    <div class="app-modal-footer">
      <button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </app-modal>
  `
})
export class AppComponent {
}

@Component({
  selector: 'app-modal',
  template: `
  <div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <ng-content select=".app-modal-header"></ng-content>
        </div>
        <div class="modal-body">
          <ng-content select=".app-modal-body"></ng-content>
        </div>
        <div class="modal-footer">
          <ng-content select=".app-modal-footer"></ng-content>
        </div>
      </div>
    </div>
  </div>
  `
})
export class ModalComponent {

  public visible = false;
  public visibleAnimate = false;

  public show(): void {
    this.visible = true;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}

To show the backdrop, you'll need something like this CSS:

.modal {
  background: rgba(0,0,0,0.6);
}

The example now allows for multiple modals at the same time. (see the onContainerClicked() method).

For Bootstrap 4 css users, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line: [ngClass]="{'in': visibleAnimate}" should be changed to: [ngClass]="{'show': visibleAnimate}"

To demonstrate, here is a plunkr

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

Laravel - Eloquent or Fluent random row

I have table with thousands of records, so I need something fast. This is my code for pseudo random row:

// count all rows with flag active = 1
$count = MyModel::where('active', '=', '1')->count(); 

// get random id
$random_id = rand(1, $count - 1);  

// get first record after random id
$data = MyModel::where('active', '=', '1')->where('id', '>', $random_id)->take(1)->first(); 

Difference between Pig and Hive? Why have both?

Pig is useful for ETL kind of workloads generally speaking. For example set of transformations you need to do to your data every day.

Hive shines when you need to run adhoc queries or just want to explore data. It sometimes can act as interface to your visualisation Layer ( Tableau/Qlikview).

Both are essential and serve different purpose.

json_decode returns NULL after webservice call

Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.

Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:

0 = JSON_ERROR_NONE

1 = JSON_ERROR_DEPTH

2 = JSON_ERROR_STATE_MISMATCH

3 = JSON_ERROR_CTRL_CHAR

4 = JSON_ERROR_SYNTAX

5 = JSON_ERROR_UTF8

In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:

'\'title\' error ...'

After that is really just an easy fix.

$json = json_decode(stripslashes($response));
if (json_last_error() == 0) { // you've got an object in $json}

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

Is it a bad practice to use an if-statement without curly braces?

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.

jQuery prevent change for select

None of the other answers worked for me, here is what eventually did.

I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.

<body>
    <select id="sel">
        <option value="Apple">Apple</option>        <!-- Must use the value attribute on the options in order for this to work. -->
        <option value="Bannana">Bannana</option>
        <option value="Cherry">Cherry</option>
    </select>
</body>

<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>

<script>
    $(document).ready()
    {
        //
        // Register the necessary events.
        $("#sel").on("click", sel_TrackLastChange);
        $("#sel").on("keydown", sel_TrackLastChange);
        $("#sel").on("change", sel_Change);
        
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // Track the previously selected value when the user either clicks on or uses the keyboard to change
    // the option in the select box.  Store it in the select box's data-* attribute.
    function sel_TrackLastChange()
    {
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // When the option changes on the select box, ask the user if they want to change it.
    function sel_Change()
    {
        if(!confirm("Are you sure?"))
        {
            //
            // If the user does not want to change the selection then use JQuery's .val() method to change
            // the selection back to what it was  previously.
            $("#sel").val($("#sel").data("lastSelected"));
        }
    }
</script>

I hope this can help someone else who has the same problem as I did.

How to find all trigger associated with a table with SQL Server?

select * from information_schema.TRIGGERS;

Select a date from date picker using Selenium webdriver

here i show you my orignal code for automating jqueryui calender from its official site "https://jqueryui.com/resources/demos/datepicker/default.html".

copy paste the code and see it working like charm :)

vote up if you like it :) regards Avadh Goyal


public class JQueryDatePicker2 {
static int targetDay = 0, targetMonth = 0, targetYear = 0;

static int currenttDate = 0, currenttMonth = 0, currenttYear = 0;

static int jumMonthBy = 0;

static boolean increment = true;

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    String dateToSet = "16/12/2016";

    getCurrentDayMonth();
    System.out.println(currenttDate);
    System.out.println(currenttMonth);
    System.out.println(currenttYear);

    getTargetDayMonthYear(dateToSet);
    System.out.println(targetDay);
    System.out.println(targetMonth);
    System.out.println(targetYear);

    calculateToHowManyMonthToJump();
    System.out.println(jumMonthBy);
    System.out.println(increment);

    System.setProperty("webdriver.chrome.driver",
            "C:\\Users\\avadh.goyal\\Desktop\\selenium-2.52.0\\web driver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.navigate().to(
            "https://jqueryui.com/resources/demos/datepicker/default.html");
    driver.manage().window().maximize();
    Thread.sleep(3000);

    driver.findElement(By.xpath("//*[@id='datepicker']")).click();

    for (int i = 0; i < jumMonthBy; i++) {
        if (increment) {
            driver.findElement(
                    By.xpath("//*[@id='ui-datepicker-div']/div/a[2]/span"))
                    .click();
        } else {
            driver.findElement(
                    By.xpath("//*[@id='ui-datepicker-div']/div/a[1]/span"))
                    .click();
        }
        Thread.sleep(1000);

    }

    driver.findElement(By.linkText(Integer.toString(targetDay))).click();

}

public static void getCurrentDayMonth() {

    Calendar cal = Calendar.getInstance();
    currenttDate = cal.get(Calendar.DAY_OF_MONTH);
    currenttMonth = cal.get(Calendar.MONTH) + 1;
    currenttYear = cal.get(Calendar.YEAR);
}

public static void getTargetDayMonthYear(String dateString) {
    int firstIndex = dateString.indexOf("/");
    int lastIndex = dateString.lastIndexOf("/");

    String day = dateString.substring(0, firstIndex);
    targetDay = Integer.parseInt(day);

    String month = dateString.substring(firstIndex + 1, lastIndex);
    targetMonth = Integer.parseInt(month);

    String year = dateString.substring(lastIndex + 1, dateString.length());
    targetYear = Integer.parseInt(year);

}

public static void calculateToHowManyMonthToJump() {

    if ((targetMonth - currenttMonth) > 0) {
        jumMonthBy = targetMonth - currenttMonth;

    } else {
        jumMonthBy = currenttMonth - targetMonth;
        increment = false;
    }
}

}

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Source

So as others mentioned, it's a convention.

How to create an Oracle sequence starting with max value from a table?

You can't use a subselect inside a CREATE SEQUENCE statement. You'll have to select the value beforehand.

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

how to find 2d array size in c++

Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},
                   {6, 7, 8, 9, 0}
                 };

  int rows =  sizeof ary / sizeof ary[0]; // 2 rows  

  int cols = sizeof ary[0] / sizeof(int); // 5 cols

How can I multiply all items in a list together with Python?

Here's some performance measurements from my machine. Relevant in case this is performed for small inputs in a long-running loop:

import functools, operator, timeit
import numpy as np

def multiply_numpy(iterable):
    return np.prod(np.array(iterable))

def multiply_functools(iterable):
    return functools.reduce(operator.mul, iterable)

def multiply_manual(iterable):
    prod = 1
    for x in iterable:
        prod *= x

    return prod

sizesToTest = [5, 10, 100, 1000, 10000, 100000]

for size in sizesToTest:
    data = [1] * size

    timerNumpy = timeit.Timer(lambda: multiply_numpy(data))
    timerFunctools = timeit.Timer(lambda: multiply_functools(data))
    timerManual = timeit.Timer(lambda: multiply_manual(data))

    repeats = int(5e6 / size)
    resultNumpy = timerNumpy.timeit(repeats)
    resultFunctools = timerFunctools.timeit(repeats)
    resultManual = timerManual.timeit(repeats)
    print(f'Input size: {size:>7d} Repeats: {repeats:>8d}    Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')

Results:

Input size:       5 Repeats:  1000000    Numpy: 4.670, Functools: 0.586, Manual: 0.459
Input size:      10 Repeats:   500000    Numpy: 2.443, Functools: 0.401, Manual: 0.321
Input size:     100 Repeats:    50000    Numpy: 0.505, Functools: 0.220, Manual: 0.197
Input size:    1000 Repeats:     5000    Numpy: 0.303, Functools: 0.207, Manual: 0.185
Input size:   10000 Repeats:      500    Numpy: 0.265, Functools: 0.194, Manual: 0.187
Input size:  100000 Repeats:       50    Numpy: 0.266, Functools: 0.198, Manual: 0.185

You can see that Numpy is quite a bit slower on smaller inputs, since it allocates an array before multiplication is performed. Also, watch out for the overflow in Numpy.

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

How do I delete NuGet packages that are not referenced by any project in my solution?

From the Package Manager console window, often whatever command you used to install a package can be used to uninstall that package. Simply replace the INSTALL command with UNINSTALL.

For example, to install PowerTCPTelnet, the command is:

Install-Package PowerTCPTelnet -Version 4.4.9

To uninstall same, the command is:

Uninstall-Package PowerTCPTelnet -Version 4.4.9

Check whether user has a Chrome extension installed

A lot of the answers here so far are Chrome only or incur an HTTP overhead penalty. The solution that we are using is a little different:

1. Add a new object to the manifest content_scripts list like so:

{
  "matches": ["https://www.yoursite.com/*"],
  "js": [
    "install_notifier.js"
  ],
  "run_at": "document_idle"
}

This will allow the code in install_notifier.js to run on that site (if you didn't already have permissions there).

2. Send a message to every site in the manifest key above.

Add something like this to install_notifier.js (note that this is using a closure to keep the variables from being global, but that's not strictly necessary):

// Dispatch a message to every URL that's in the manifest to say that the extension is
// installed.  This allows webpages to take action based on the presence of the
// extension and its version. This is only allowed for a small whitelist of
// domains defined in the manifest.
(function () {
  let currentVersion = chrome.runtime.getManifest().version;
  window.postMessage({
    sender: "my-extension",
    message_name: "version",
    message: currentVersion
  }, "*");
})();

Your message could say anything, but it's useful to send the version so you know what you're dealing with. Then...

3. On your website, listen for that message.

Add this to your website somewhere:

window.addEventListener("message", function (event) {
  if (event.source == window &&
    event.data.sender &&
    event.data.sender === "my-extension" &&
    event.data.message_name &&
    event.data.message_name === "version") {
    console.log("Got the message");
  }
});

This works in Firefox and Chrome, and doesn't incur HTTP overhead or manipulate the page.

Timestamp with a millisecond precision: How to save them in MySQL

You can use BIGINT as follows:

CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
   );

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

You can use the Validation plugin with its number() method.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

WAMP server, localhost is not working

Goto This link its working..

http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/

Update: Using XAMP

After I’ve written this blog post I’ve figured out that XAMP, although very similar to WAMP, doesn’t force you to run Apache as a service, instead it can run it as a regular process. So I ended up using XAMP, and changed Apache port to 8080 so now everything works.

WAMP Issues

If you have Window 7 or later you may have come across issues with WAMP server trying to start Apache service on port 80 and failing.

There are many conflict and issues that might have come up. Before you try anything, check if you have ZoneAlarm, Nod32, or any other program/firewall that might be blocking Apache server. If you’re sure that firewall isn’t the problem here is a couple of fixes that you can try.

NOTE: After every fix you try, you must click on yellow WAMP icon and choose Restart All Services

Checking which process is causing the problem

Open Command Prompt window by typing cmd in Run command box or Start Search, and hit Enter. Type in the following command: netstat -o -n -a | findstr 0.0:80 The last column of each row is the process identified (process ID or PID). Identify which process or application is using the port by matching the PID against PID number in Task Manager. If you don’t see PID column in your Task Manager you need to go to Processes tab -> View Menu -> Select Columns and choose PID from the list Now, you may have identified application that reserves port 80, or you may have found out that System is using your port 80. That means that one of internal services is using your port, in which case continue reading further. Conflict with Skype

If you found out that Skype is using your port 80, you need to change some settings in Skype. On Windows, Skype reserves port 80 which is used for HTTP. Apache requires this port. So if you’re running Skype, you must go to Tools > Options. Then in the Advanced section, select Connection. Un-check the box that says “Use port 80 and 443 as alternatives for incoming connection“. Quit Skype and restart. The issue should be resolved.

Conflict with IIS Server

IIS Server and Apache are both web server that use port 80 so they might be in conflict. Try stopping IIS by:

Going into Control Panel -> Administrative Tools -> Internet Information Services Right click on Default Web Site Click on Stop option in the popup menu, and see of the listener on port 80 has cleared. Conflict with MS SQL Server

MS SQL Server installs “SQL Server Reporting Services (MSSQLSERVER)” that apparently defaults to 80. You can try stopping it to free up port 80.

Go to Control Panel -> Administrative Tools -> Services There find MSSQLSERVER (might be found also under SQL Server) Double click it -> Click Stop Under Startup type: choose Manual Other Services that can cause conflicts

As described above for MS SQL Server:

Go to Control Panel -> Administrative Tools -> Services You can try stopping: Web Deployment Agent Service Windows Remote Management Autodesk EDM Server World Wide Web Publishing Service There are probably more of them, but this where the ones that I tryed.

Try turning off HTTP driver directly

If you’ve tried everything mentioned above and your WAMP server is still not working you could try this (which eventually helped me).

Right click on My Computer icon -> Properties Go to Device Manager Click on View menu and chooseShow hidden devices Now from the list choose Non-Plug and Play devices Double click HTTP -> go to Driver For Type choose Disabled Restart your computer After your computer boots up you should be able to start up WAMP server.

If everything else fails

You could try changing Apache server to listen to some other port other than port 80.

Click on yellow WAMP icon in your taskbar Choose Apache -> httpd.conf Inside find these two lines of code:

Listen 80 ServerName localhost:80 and change them to something like this (they are not one next to the other):

Listen 8080 ServerName localhost:8080 Restart all services, and try typing localhost:8080 into your browser. WAMP server should now be working.

ggplot with 2 y axes on each side and different scales

Sometimes a client wants two y scales. Giving them the "flawed" speech is often pointless. But I do like the ggplot2 insistence on doing things the right way. I am sure that ggplot is in fact educating the average user about proper visualization techniques.

Maybe you can use faceting and scale free to compare the two data series? - e.g. look here: https://github.com/hadley/ggplot2/wiki/Align-two-plots-on-a-page

Can I check if Bootstrap Modal Shown / Hidden?

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

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

Get UTC time and local time from NSDate object

Swift 3

You can get Date based on your current timezone from UTC

extension Date {
    func currentTimeZoneDate() -> String {
        let dtf = DateFormatter()
        dtf.timeZone = TimeZone.current
        dtf.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return dtf.string(from: self)
    }
}

Call like this:

Date().currentTimeZoneDate()

Are vectors passed to functions by value or by reference in C++

when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.

How to get the unix timestamp in C#

This is what I use.

 public class TimeStamp
    {
        public Int32 UnixTimeStampUTC()
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
}

Enumerations on PHP

I have recently developed a simple library for PHP Enums: https://github.com/dnl-blkv/simple-php-enum

At the moment of writing this answer, it is still in pre-release stage, but already fully-functional, well-documented and published on Packagist.

This might be a handy option if you are looking for easy-to-implement enums similar to those of C/C++.

What is SuppressWarnings ("unchecked") in Java?

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5.

@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.

You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

Read more: https://javarevisited.blogspot.com/2015/09/what-is-suppresswarnings-annotation-in-java-unchecked-raw-serial.html#ixzz5rqQaOLUa

pythonw.exe or python.exe?

In my experience the pythonw.exe is faster at least with using pygame.

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How to validate a file upload field using Javascript/jquery

Check it's value property:

In jQuery (since your tag mentions it):

$('#fileInput').val()

Or in vanilla JavaScript:

document.getElementById('myFileInput').value

How to update data in one table from corresponding data in another table in SQL Server 2005

this works wonders - no its turn to call this procedure form code with DataTable with schema exactly matching the custType create table customer ( id int identity(1,1) primary key, name varchar(50), cnt varchar(10) )

 create type custType as table
 (
 ctId int,
 ctName varchar(20)
 )

 insert into customer values('y1', 'c1')
 insert into customer values('y2', 'c2')
 insert into customer values('y3', 'c3')
 insert into customer values('y4', 'c4')
 insert into customer values('y5', 'c5')

 declare @ct as custType 
 insert @ct (ctid, ctName) values(3, 'y33'), (4, 'y44')
 exec multiUpdate @ct

 create Proc multiUpdate (@ct custType readonly) as begin
 update customer set  Name = t.ctName  from @ct t where t.ctId = customer.id
 end

public DataTable UpdateLevels(DataTable dt)
        {
            DataTable dtRet = new DataTable();
            using (SqlConnection con = new SqlConnection(datalayer.bimCS))
            {
                SqlCommand command = new SqlCommand();
                command.CommandText = "UpdateLevels";
                command.Parameters.Clear();
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@ct", dt).SqlDbType = SqlDbType.Structured;
                command.Connection = con;
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
                {
                    dataAdapter.SelectCommand = command;
                    dataAdapter.Fill(dtRet);
                }
            }
}

Use of "global" keyword in Python

It means that you should not do the following:

x = 1

def myfunc():
  global x

  # formal parameter
  def localfunction(x):
    return x+1

  # import statement
  import os.path as x

  # for loop control target
  for x in range(10):
    print x

  # class definition
  class x(object):
    def __init__(self):
      pass

  #function definition
  def x():
    print "I'm bad"

system("pause"); - Why is it wrong?

It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.

How to view UTF-8 Characters in VIM or Gvim

I couldn't get any other fonts I installed to show up in my Windows GVim editor, so I just switched to Lucida Console which has at least somewhat better UTF-8 support. Add this to the end of your _vimrc:

" For making everything utf-8
set enc=utf-8
set guifont=Lucida_Console:h9:cANSI
set guifontwide=Lucida_Console:h12

Now I see at least some UTF-8 characters.

How to make a Java Generic method static?

public static <E> E[] appendToArray(E[] array, E item) { ...

Note the <E>.

Static generic methods need their own generic declaration (public static <E>) separate from the class's generic declaration (public class ArrayUtils<E>).

If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_):

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");

This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

100% width background image with an 'auto' height

Just use a two color background image:

<div style="width:100%; background:url('images/bkgmid.png');
       background-size: cover;">
content
</div>

npm ERR! Error: EPERM: operation not permitted, rename

npm was failing for me at scandir for:

npm install -g webpack

...which might be caused by npm attempting to "modify" files that were potentially locked by other processes as mentioned here and in few other github threads. After force cleaning the cache, verifying cache, running as admin, disabling the AV, etc the solution that actually worked for me was closing any thing that might be placing a lock the files (i.e. restarting my computer).

I hope this helps someone struggling.

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

What is the idiomatic Go equivalent of C's ternary operator?

As pointed out (and hopefully unsurprisingly), using if+else is indeed the idiomatic way to do conditionals in Go.

In addition to the full blown var+if+else block of code, though, this spelling is also used often:

index := val
if val <= 0 {
    index = -val
}

and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b, you can create a function to hold it:

func min(a, b int) int {
    if a <= b {
        return a
    }
    return b
}

...

value := min(a, b)

The compiler will inline such simple functions, so it's fast, more clear, and shorter.

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

ReactJS lifecycle method inside a function Component

Solution One: You can use new react HOOKS API. Currently in React v16.8.0

Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.

A Note from the Author of recompose (acdlite, Oct 25 2018):

Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.

Solution Two:

If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.

Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).

// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

function RenderlessComponent() {
  return null; 
}

export default lifecycle({

  componentDidMount() {
    const { checkIfAuthed } = this.props;
    // Do they have an active session? ("Remember me")
    checkIfAuthed();
  },

  componentWillReceiveProps(nextProps) {
    const {
      loadUser,
    } = this.props;

    // Various 'indicators'..
    const becameAuthed = (!(this.props.auth) && nextProps.auth);
    const isCurrentUser = (this.props.currentUser !== null);

    if (becameAuthed) {
      loadUser(nextProps.auth.uid);
    }

    const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
    if (shouldSetCurrentUser) {
      const currentUser = nextProps.users[nextProps.auth.uid];
      if (currentUser) {
        this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
        });
      }
    }
  }
})(RenderlessComponent);

How do I escape ampersands in batch files?

If you need to echo a string that contains an ampersand, quotes won't help, because you would see them on the output as well. In such a case, use for:

for %a in ("First & Last") do echo %~a

...in a batch script:

for %%a in ("First & Last") do echo %%~a

or

for %%a in ("%~1") do echo %%~a

Swift's guard keyword

From Apple documentation:

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

Synatx:

guard condition else {
    statements
}

Advantage:

1. By using guard statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.

2. It was designed specifically for exiting a method or function early.

if you use if let below is the code how it looks.

  let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            if let  statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
                if let data = data {

                    //Process Data Here.
                    print("Data: \(data)")

                } else {
                    print("No data was returned by the request!")
                }
            } else {
                print("Your request returned a status code other than 2XX!")
            }
        } else {
            print("Error Info: \(error.debugDescription)")
        }
    }
    task.resume()

Using guard you can transfer control out of a scope if one or more conditions aren't met.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            /* GUARD: was there an error? */
            guard (error == nil) else {
                print("There was an error with your request: \(error)")
                return
            }

            /* GUARD: Did we get a successful 2XX response? */
            guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2XX!")
                return
            }

            /* GUARD: was there any data returned? */
            guard let data = data else {
                print("No data was returned by the request!")
                return
            }

            //Process Data Here.
            print("Data: \(data)")
}
task.resume()

Reference:

1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement

What is `related_name` used for in Django?

The related_name argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:

class UserMapDataFrame(models.Model):
    user = models.ForeignKey(User) 

In order to access UserMapDataFrame objects from the related User, the default call would be User.usermapdataframe_set.all(), which it is quite difficult to read.

Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='map_data'), the call would then be User.map_data.all().

Disable double-tap "zoom" option in browser on touch devices

* {
    -ms-touch-action: manipulation;
    touch-action: manipulation;
}

Disable double tap to zoom on touch screens. Internet explorer included.

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

HTTP Get with 204 No Content: Is that normal

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

According to the RFC part for the status code 204, it seems to me a valid choice for a GET request.

A 404 Not Found, 200 OK with empty body and 204 No Content have completely different meaning, sometimes we can't use proper status code but bend the rules and they will come back to bite you one day or later. So, if you can use proper status code, use it!

I think the choice of GET or POST is very personal as both of them will do the work but I would recommend you to keep a POST instead of a GET, for two reasons:

  • You want the other part (the servlet if I understand correctly) to perform an action not retrieve some data from it.
  • By default GET requests are cacheable if there are no parameters present in the URL, a POST is not.

What is the most efficient way to get first and last line of a text file?

This is my solution, compatible also with Python3. It does also manage border cases, but it misses utf-16 support:

def tail(filepath):
    """
    @author Marco Sulla ([email protected])
    @date May 31, 2016
    """

    try:
        filepath.is_file
        fp = str(filepath)
    except AttributeError:
        fp = filepath

    with open(fp, "rb") as f:
        size = os.stat(fp).st_size
        start_pos = 0 if size - 1 < 0 else size - 1

        if start_pos != 0:
            f.seek(start_pos)
            char = f.read(1)

            if char == b"\n":
                start_pos -= 1
                f.seek(start_pos)

            if start_pos == 0:
                f.seek(start_pos)
            else:
                char = ""

                for pos in range(start_pos, -1, -1):
                    f.seek(pos)

                    char = f.read(1)

                    if char == b"\n":
                        break

        return f.readline()

It's ispired by Trasp's answer and AnotherParker's comment.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

List of all index & index columns in SQL Server DB

with connect(schema_name,table_name,index_name,index_column_id,column_name) as
(   select s.name schema_name, t.name table_name, i.name index_name, index_column_id, cast(c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id
                where index_column_id=1
union all
select s.name schema_name, t.name table_name, i.name index_name, ic.index_column_id, cast(connect.column_name + ',' + c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id join connect on
connect.index_column_id+1 = ic.index_column_id
and connect.schema_name = s.name
and connect.table_name = t.name
and connect.index_name = i.name)
select connect.schema_name,connect.table_name,connect.index_name,connect.column_name
from connect join (select schema_name,table_name,index_name,MAX(index_column_id) index_column_id
from connect group by schema_name,table_name,index_name) mx
on connect.schema_name = mx.schema_name
and connect.table_name = mx.table_name
and connect.index_name = mx.index_name
and connect.index_column_id = mx.index_column_id
order by 1,2,3

How to check if a variable is an integer or a string?

Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.

intresult = None
while intresult is None:
    input = raw_input()
    try: intresult = int(input)
    except ValueError: pass

Cannot read configuration file due to insufficient permissions

check if the file is not marked as read-only, despite of the IIS_IUSRS permission it will display the same message.

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

android View not attached to window manager

After a fight with this issue, I finally end up with this workaround:

/**
 * Dismiss {@link ProgressDialog} with check for nullability and SDK version
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissProgressDialog(ProgressDialog dialog) {
    if (dialog != null && dialog.isShowing()) {

            //get the Context object that was used to great the dialog
            Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

            // if the Context used here was an activity AND it hasn't been finished or destroyed
            // then dismiss it
            if (context instanceof Activity) {

                // Api >=17
                if (!((Activity) context).isFinishing() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isDestroyed()) {
                            dismissWithExceptionHandling(dialog);
                        }
                    } else { 
                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        dismissWithExceptionHandling(dialog);
                    }
                }
            } else
                // if the Context used wasn't an Activity, then dismiss it too
                dismissWithExceptionHandling(dialog);
        }
        dialog = null;
    }
}

/**
 * Dismiss {@link ProgressDialog} with try catch
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissWithExceptionHandling(ProgressDialog dialog) {
    try {
        dialog.dismiss();
    } catch (final IllegalArgumentException e) {
        // Do nothing.
    } catch (final Exception e) {
        // Do nothing.
    } finally {
        dialog = null;
    }
}

Sometimes, good exception handling works well if there wasn't a better solution for this issue.

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

Jenkins Git Plugin: How to build specific tag?

In a latest Jenkins (1.639 and above) you can:

  1. just specify name of tag in a field 'Branches to build'.
  2. in a parametrized build you can use parameter as variable in a same field 'Branches to build' i.e. ${Branch_to_build}.
  3. you can install Git Parameter Plugin which will provide to you functionality by listing of all available branches and tags.

How can I show a combobox in Android?

For a combobox (http://en.wikipedia.org/wiki/Combo_box) which allows free text input and has a dropdown listbox I used a AutoCompleteTextView as suggested by vbence.

I used the onClickListener to display the dropdown list box when the user selects the control.

I believe this resembles this kind of a combobox best.

private static final String[] STUFF = new String[] { "Thing 1", "Thing 2" };

public void onCreate(Bundle b) {
    final AutoCompleteTextView view = 
        (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);

    view.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
                view.showDropDown();
        }
    });

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this, 
        android.R.layout.simple_dropdown_item_1line,
        STUFF
    );
    view.setAdapter(adapter);
}

Drawing Isometric game worlds

Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.

After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

ASP.NET IIS Web.config [Internal Server Error]

I experienced the same issue, and found out that the applicationdeployed was of .NET version 3.5, but the Application pool was using .NET 2.0. That caused the problem you described above. Hope it helps someone.

My error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core 
Notification BeginRequest 
Handler Not yet determined 
Error Code 0x80070021 

Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".  
Config File \\?\C:\inetpub\MyService\web.config 
Requested URL http://localhost:80/MyService.svc 
Physical Path C:\inetpub\DeployService\DeployService.svc 
Logon Method Not yet determined 
Logon User Not yet determined 
 Config Source
101:        </modules>
  102:      <handlers>
  103:          <remove name="WebServiceHandlerFactory-Integrated"/>
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core 
Notification BeginRequest 
Handler Not yet determined 
Error Code 0x80070021 
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".  

Config File \\?\C:\inetpub\DeployService\web.config 
Requested URL http://localhost:80/DeployService.svc 
Physical Path C:\inetpub\DeployService\DeployService.svc 
Logon Method Not yet determined 
Logon User Not yet determined 
 Config Source
  101:      </modules>
  102:      <handlers>
  103:          <remove name="WebServiceHandlerFactory-Integrated"/>`

Print PDF directly from JavaScript

I used this function to download pdf stream from server.

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // iframe.id = 'pdfIframe'
        iframe.className='pdfIframe'
        document.body.appendChild(iframe);
        iframe.style.display = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                iframe.focus();
                iframe.contentWindow.print();
                URL.revokeObjectURL(url)
                // document.body.removeChild(iframe)
            }, 1);
        };
        iframe.src = url;
        // URL.revokeObjectURL(url)
    }

Using msbuild to execute a File System Publish Profile

FYI: I had the same issue with Visual Studio 2015. After many of hours trying, I can now do msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=myprofile.

I had to edit my .csproj file to get it working. It contained a line like this:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" 
  Condition="false" />

I changed this line as follows:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets" />

(I changed 10.0 to 14.0, not sure whether this was necessary. But I definitely had to remove the condition part.)

Bootstrap modal in React.js

I was recently looking for a nice solution to this without adding React-Bootstrap to my project (as Bootstrap 4 is about to be released).

This is my solution: https://jsfiddle.net/16j1se1q/1/

let Modal = React.createClass({
    componentDidMount(){
        $(this.getDOMNode()).modal('show');
        $(this.getDOMNode()).on('hidden.bs.modal', this.props.handleHideModal);
    },
    render(){
        return (
          <div className="modal fade">
            <div className="modal-dialog">
              <div className="modal-content">
                <div className="modal-header">
                  <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                  <h4 className="modal-title">Modal title</h4>
                </div>
                <div className="modal-body">
                  <p>One fine body&hellip;</p>
                </div>
                <div className="modal-footer">
                  <button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
                  <button type="button" className="btn btn-primary">Save changes</button>
                </div>
              </div>
            </div>
          </div>
        )
    },
    propTypes:{
        handleHideModal: React.PropTypes.func.isRequired
    }
});



let App = React.createClass({
    getInitialState(){
        return {view: {showModal: false}}
    },
    handleHideModal(){
        this.setState({view: {showModal: false}})
    },
    handleShowModal(){
        this.setState({view: {showModal: true}})
    },
    render(){
    return(
        <div className="row">
            <button className="btn btn-default btn-block" onClick={this.handleShowModal}>Open Modal</button>
            {this.state.view.showModal ? <Modal handleHideModal={this.handleHideModal}/> : null}
        </div>
    );
  }
});

React.render(
   <App />,
    document.getElementById('container')
);

The main idea is to only render the Modal component into the React DOM when it is to be shown (in the App components render function). I keep some 'view' state that indicates whether the Modal is currently shown or not.

The 'componentDidMount' and 'componentWillUnmount' callbacks either hide or show the modal (once it is rendered into the React DOM) via Bootstrap javascript functions.

I think this solution nicely follows the React ethos but suggestions are welcome!

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

How to convert .pfx file to keystore with private key?

I found this page which tells you how to import a PFX to JKS (Java Key Store):

keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME

Can scripts be inserted with innerHTML?

I had this problem with innerHTML, I had to append a Hotjar script to the "head" tag of my Reactjs application and it would have to execute right after appending.

One of the good solutions for dynamic Node import into the "head" tag is React-helment module.


Also, there is a useful solution for the proposed issue:

No script tags in innerHTML!

It turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So the following will not execute and there will be no alert saying Hello World!

element.innerHTML = "<script>alert('Hello World!')</script>";

This is documented in the HTML5 spec:

Note: script elements inserted using innerHTML do not execute when they are inserted.

But beware, this doesn't mean innerHTML is safe from cross-site scripting. It is possible to execute JavaScript via innerHTML without using tags as illustrated on MDN's innerHTML page.

Solution: Dynamically adding scripts

To dynamically add a script tag, you need to create a new script element and append it to the target element.

You can do this for external scripts:

var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);

And inline scripts:

var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");
newScript.appendChild(inlineScript); 
target.appendChild(newScript);

Emulate Samsung Galaxy Tab

UPDATED:
Matt provided a great link on how to add emulators for all Samsung devices.

OLD:
To get the official Samsung Galaxy Tab emulator do the following:

  1. Open the Android SDK and AVD Manager
  2. Click on Available packages
  3. Expand the Third party Add-ons. There you will see Samsung Electronics add-ons.
  4. Once the add-on is installed create a new emulator. Under Target you will see the new Samsung Tab settings, select that.

That's it!

How to dynamically change the color of the selected menu item of a web page?

Assuming you want to change the colour of the currently selected link/tab... you're best bet is to apply a class (say active) to the currently selected link/tab and then style this differently.

Example style could be:

li.active, a.active {
  background-color: #f90;
}

Writing Unicode text to a text file?

In case of writing in python3

>>> a = u'bats\u00E0'
>>> print a
batsà
>>> f = open("/tmp/test", "w")
>>> f.write(a)
>>> f.close()
>>> data = open("/tmp/test").read()
>>> data
'batsà'

In case of writing in python2:

>>> a = u'bats\u00E0'
>>> f = open("/tmp/test", "w")
>>> f.write(a)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:

>>> f.write(a.encode("utf-8"))
>>> f.close()

and decode the data while reading using the codecs "utf-8":

>>> data = open("/tmp/test").read()
>>> data.decode("utf-8")
u'bats\xe0'

And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this

>>> print a
batsà

CSS: fixed to bottom and centered

I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look

#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}

then in html...

<div id="enclose">
    <div id="problem">
    <!--this is where the text/markup would go-->
    </div>
</div>

There ya go!
-Hypertextie

Git commit with no commit message

I found the simplest solution:

git commit -am'save'

That's all,you will work around git commit message stuff.

you can even save that commend to a bash or other stuff to make it more simple.

Our team members always write those messages,but almost no one will see those message again.

Commit message is a time-kill stuff at least in our team,so we ignore it.

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Active Directory LDAP Query by sAMAccountName and Domain

You have to perform your search in the domain:

http://msdn.microsoft.com/en-us/library/ms677934(VS.85).aspx So, basically your should bind to a domain in order to search inside this domain.

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

How to simulate target="_blank" in JavaScript

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

How to change option menu icon in the action bar?

The following lines should be updated in app -> main -> res -> values -> Styles.xml

 <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
</style>

<!-- Style to replace actionbar overflow icon. set item 'android:actionOverflowButtonStyle' in AppTheme -->
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_launcher</item>
    <item name="android:background">?android:attr/actionBarItemBackground</item>
    <item name="android:contentDescription">"Lala"</item>
</style>

This is how it can be done. If you want to change the overflow icon in action bar

Access POST values in Symfony2 request object

The form post values are stored under the name of the form in the request. For example, if you've overridden the getName() method of ContactType() to return "contact", you would do this:

$postData = $request->request->get('contact');
$name_value = $postData['name'];

If you're still having trouble, try doing a var_dump() on $request->request->all() to see all the post values.

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

rotating axis labels in R

First, create the data for the chart

H <- c(1.964138757, 1.729143013,    1.713273714,    1.706771799,    1.67977205)
M <- c("SP105", "SP30", "SP244", "SP31",    "SP147")

Second, give the name for a chart file

png(file = "Bargraph.jpeg", width = 500, height = 300)

Third, Plot the bar chart

barplot(H,names.arg=M,ylab="Degree ", col= rainbow(5), las=2, border = 0, cex.lab=1, cex.axis=1, font=1,col.axis="black")
title(xlab="Service Providers", line=4, cex.lab=1)

Finally, save the file

dev.off()

Output:

enter image description here

php REQUEST_URI

Since vars passed through url are $_GET vars, you can use filter_input() function:

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

It would store the values of each var and sanitize/validate them too.

C# Return Different Types?

If you can make a abstract class for all the possibilities then that is highly recommended:

public Hardware GetAnything()
{
     Computer computer = new Computer();

     return computer;    
}

abstract Hardware {

}

class Computer : Hardware {

}

Or an interface:

interface IHardware {

}

class Computer : IHardware {

}

If it can be anything then you could consider using "object" as your return type, because every class derives from object.

public object GetAnything()
{
     Hello hello = new Hello();

     return hello;    
}

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

pandas groupby sort descending order

Other instance of preserving the order or sort by descending:

In [97]: import pandas as pd                                                                                                    

In [98]: df = pd.DataFrame({'name':['A','B','C','A','B','C','A','B','C'],'Year':[2003,2002,2001,2003,2002,2001,2003,2002,2001]})

#### Default groupby operation:
In [99]: for each in df.groupby(["Year"]): print each                                                                           
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)

### order preserved:
In [100]: for each in df.groupby(["Year"], sort=False): print each                                                               
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)

In [106]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"]))                        
Out[106]: 
        Year name
Year             
2003 0  2003    A
     3  2003    A
     6  2003    A
2002 1  2002    B
     4  2002    B
     7  2002    B
2001 2  2001    C
     5  2001    C
     8  2001    C

In [107]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"])).reset_index(drop=True)
Out[107]: 
   Year name
0  2003    A
1  2003    A
2  2003    A
3  2002    B
4  2002    B
5  2002    B
6  2001    C
7  2001    C
8  2001    C

python: How do I know what type of exception occurred?

Just refrain from catching the exception and the traceback that Python prints will tell you what exception occurred.

How to compare two dates along with time in java

An Alternative is....

Convert both dates into milliseconds as below

Date d = new Date();
long l = d.getTime();

Now compare both long values

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

Filtering a list of strings based on contents

Tried this out quickly in the interactive shell:

>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>

Why does this work? Because the in operator is defined for strings to mean: "is substring of".

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
   if 'ab' in s:
       result.append(s)

Java multiline string

When a long series of + are used, only one StringBuilder is created, unless the String is determined at compile time in which case no StringBuilder is used!

The only time StringBuilder is more efficient is when multiple statements are used to construct the String.

String a = "a\n";
String b = "b\n";
String c = "c\n";
String d = "d\n";

String abcd = a + b + c + d;
System.out.println(abcd);

String abcd2 = "a\n" +
        "b\n" +
        "c\n" +
        "d\n";
System.out.println(abcd2);

Note: Only one StringBuilder is created.

  Code:
   0:   ldc     #2; //String a\n
   2:   astore_1
   3:   ldc     #3; //String b\n
   5:   astore_2
   6:   ldc     #4; //String c\n
   8:   astore_3
   9:   ldc     #5; //String d\n
   11:  astore  4
   13:  new     #6; //class java/lang/StringBuilder
   16:  dup
   17:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   20:  aload_1
   21:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   24:  aload_2
   25:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   28:  aload_3
   29:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   32:  aload   4
   34:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   37:  invokevirtual   #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   40:  astore  5
   42:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   45:  aload   5
   47:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   50:  ldc     #12; //String a\nb\nc\nd\n
   52:  astore  6
   54:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   57:  aload   6
   59:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   62:  return

To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.

Make it as clear and simple as you can.

ie8 var w= window.open() - "Message: Invalid argument."

If you want use the name of new window etc posting a form to this window, then the solution, that working in IE, FF, Chrome:

  var ret = window.open("", "_blank");
  ret.name = "NewFormName";

  var myForm = document.createElement("form");
  myForm.method="post";
  myForm.action = "xyz.php";
  myForm.target = "NewFormName";

      ...

Python != operation vs "is not"

>>> () is ()
True
>>> 1 is 1
True
>>> (1,) == (1,)
True
>>> (1,) is (1,)
False
>>> a = (1,)
>>> b = a
>>> a is b
True

Some objects are singletons, and thus is with them is equivalent to ==. Most are not.

Update select2 data without rebuilding the control

var selBoxObj = $('#selectpill');
selBoxObj.trigger("change.select2");

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;

$mysqladmin -u root -p[your root password here] version Which outputs:

    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Server version      5.5.49-0ubuntu0.14.04.1
    Protocol version    10
    Connection      Localhost via UNIX socket
    UNIX socket     /var/run/mysqld/mysqld.sock
    Uptime:         1 hour 54 min 3 sec

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

    $cfg['Servers'][$i]['host'] = 'localhost';
    $cfg['Servers'][$i]['connect_type'] = 'socket';
    $cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';

All credit goes to this person: This is the correct solution

Sorting arraylist in alphabetical order (case insensitive)

KOTLIN DEVELOPERS

For Custome List, if you want to sort based on one String then you can use this:

phoneContactArrayList.sortWith(Comparator { item, t1 ->
        val s1: String = item.phoneContactUserName
        val s2: String = t1.phoneContactUserName
        s1.compareTo(s2, ignoreCase = true)
    })

Find size of object instance in bytes in c#

I have created benchmark test for different collections in .NET: https://github.com/scholtz/TestDotNetCollectionsMemoryAllocation

Results are as follows for .NET Core 2.2 with 1,000,000 of objects with 3 properties allocated:

Testing with string: 1234567
Hashtable<TestObject>:                                     184 672 704 B
Hashtable<TestObjectRef>:                                  136 668 560 B
Dictionary<int, TestObject>:                               171 448 160 B
Dictionary<int, TestObjectRef>:                            123 445 472 B
ConcurrentDictionary<int, TestObject>:                     200 020 440 B
ConcurrentDictionary<int, TestObjectRef>:                  152 026 208 B
HashSet<TestObject>:                                       149 893 216 B
HashSet<TestObjectRef>:                                    101 894 384 B
ConcurrentBag<TestObject>:                                 112 783 256 B
ConcurrentBag<TestObjectRef>:                               64 777 632 B
Queue<TestObject>:                                         112 777 736 B
Queue<TestObjectRef>:                                       64 780 680 B
ConcurrentQueue<TestObject>:                               112 784 136 B
ConcurrentQueue<TestObjectRef>:                             64 783 536 B
ConcurrentStack<TestObject>:                               128 005 072 B
ConcurrentStack<TestObjectRef>:                             80 004 632 B

For memory test I found the best to be used

GC.GetAllocatedBytesForCurrentThread()

Python multiprocessing PicklingError: Can't pickle <type 'function'>

Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.

import dill
import itertools
def run_dill_encoded(payload):
    fun, args = dill.loads(payload)
    res = fun(*args)
    res = dill.dumps(res)
    return res

def dill_map_async(pool, fun, args_list,
                   as_tuple=True,
                   **kw):
    if as_tuple:
        args_list = ((x,) for x in args_list)

    it = itertools.izip(
        itertools.cycle([fun]),
        args_list)
    it = itertools.imap(dill.dumps, it)
    return pool.map_async(run_dill_encoded, it, **kw)

if __name__ == '__main__':
    import multiprocessing as mp
    import sys,os
    p = mp.Pool(4)
    res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
                  [lambda x:x+1]*10,)
    res = res.get(timeout=100)
    res = map(dill.loads,res)
    print(res)

What is the difference between a .cpp file and a .h file?

The .cpp file is the compilation unit : it's the real source code file that will be compiled (in C++).

The .h (header) files are files that will be virtually copy/pasted in the .cpp files where the #include precompiler instruction appears. Once the headers code is inserted in the .cpp code, the compilation of the .cpp can start.

How do I return a char array from a function?

A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {
    char* arr = malloc(100);
    strcpy(arr,"xxxx");
    return arr;
}

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

Get selected value/text from Select on change

Use

document.getElementById("select_id").selectedIndex

Or to get the value:

document.getElementById("select_id").value

Assign a login to a user created without login (SQL Server)

You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run CREATE LOGIN first.

If the database level user is

  • a Windows Login, the mapping will be fixed automatcially via the AD SID
  • a SQL Login, use "sid" from sys.database_principals for the SID option for the login

Then run ALTER USER

Edit, after comments and updates

The sid from sys.database_principals is for a Windows login.

So trying to create and re-map to a SQL Login will fail

Run this to get the Windows login

SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)

Counting lines, words, and characters within a text file using Python

Try this:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

Back to your code:

fname = "feed.txt"
fname = open('feed.txt', 'r')

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

for line in feed:
    lines = line.split('\n')

line is one line from the file. It does not make sense to split('\n') it.

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

Processing $http response in service

When binding the UI to your array you'll want to make sure you update that same array directly by setting the length to 0 and pushing the data into the array.

Instead of this (which set a different array reference to data which your UI won't know about):

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data = d;
    });
  };

try this:

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data.length = 0;
      for(var i = 0; i < d.length; i++){
        data.push(d[i]);
      }
    });
  };

Here is a fiddle that shows the difference between setting a new array vs emptying and adding to an existing one. I couldn't get your plnkr working but hopefully this works for you!

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

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])]