Programs & Examples On #Foreach

foreach is a looping construct that executes a given piece of code for each element in a list/collection/array. In contrast to a for loop, the foreach loop doesn't require the coder to maintain a counter variable to avoid off-by-one (fencepost) bugs.It is recommended to use when simple iteration over whole array/list/collection is needed.

change values in array when doing foreach

To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);
    };
});
console.log(values);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

To insert elements before:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');
};

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

To insert elements after:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');
};

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

To replace an element:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');
};

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

How to get a index value from foreach loop in jstl

You can use the varStatus attribute like this:-

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.

Hence, you can send that to your javascript method like this:-

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

Foreach loop in java for a custom object list

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

laravel foreach loop in controller

Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:

$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();

Further you may also make sure if $products has data:

if($product) {
    return View:make('viewname')->with('products', $products);
}

Then in the view:

foreach ($products as $product) {
    // If Product has sku (collection object, probably related models)
    foreach ($product->sku as $sku) {
        // Code Here        
    }
}

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

You can't directly get an iterator for an array.

But you can use a List, backed by your array, and get an ierator on this list. For that, your array must be an Integer array (instead of an int array):

Integer[] arr={1,2,3};
List<Integer> arrAsList = Arrays.asList(arr);
Iterator<Integer> iter = arrAsList.iterator();

Note: it is only theory. You can get an iterator like this, but I discourage you to do so. Performances are not good compared to a direct iteration on the array with the "extended for syntax".

Note 2: a list construct with this method doesn't support all methods (since the list is backed by the array which have a fixed size). For example, "remove" method of your iterator will result in an exception.

Is there a way to access an iteration-counter in Java's for-each loop?

The best and optimized solution is to do the following thing:

int i=0;

for(Type t: types) {
  ......
  i++;
}

Where Type can be any data type and types is the variable on which you are applying for a loop.

Performance of FOR vs FOREACH in PHP

I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:

  1. If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.

  2. Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.

  3. Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.

  4. But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.

  5. What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.

For these reasons foreach is understandably the best option for simple iteration.

And don't forget, it's also the easiest to read, so it's win-win.

"continue" in cursor.forEach()

In my opinion the best approach to achieve this by using the filter method as it's meaningless to return in a forEach block; for an example on your snippet:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

This will narrow down your elementsCollection and just keep the filtred elements that should be processed.

How to loop through a collection that supports IEnumerable?

A regular for each will do:

foreach (var item in collection)
{
    // do your stuff   
}

Java 8 forEach with index

There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:

int idx = 0;
for (Param p : params) query.bind(idx++, p);

Or the older style:

for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));

Get next element in foreach loop

You could get the keys of the array before the foreach, then use a counter to check the next element, something like:

//$arr is the array you wish to cycle through
$keys = array_keys($arr);
$num_keys = count($keys);
$i = 1;
foreach ($arr as $a)
{
    if ($i < $num_keys && $arr[$keys[$i]] == $a)
    {
        // we have a match
    }
    $i++;
}

This will work for both simple arrays, such as array(1,2,3), and keyed arrays such as array('first'=>1, 'second'=>2, 'thrid'=>3).

Calling remove in foreach loop in Java

  1. Try this 2. and change the condition to "WINTER" and you will wonder:
public static void main(String[] args) {
  Season.add("Frühling");
  Season.add("Sommer");
  Season.add("Herbst");
  Season.add("WINTER");
  for (String s : Season) {
   if(!s.equals("Sommer")) {
    System.out.println(s);
    continue;
   }
   Season.remove("Frühling");
  }
 }

Java foreach loop: for (Integer i : list) { ... }

Sometimes it's just better to use an iterator.

(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a String join method (which you can easily do without).)

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

Automatically get loop index in foreach loop in Perl

Well, there is this way:

use List::Rubyish;

$list = List::Rubyish->new( [ qw<a b c> ] );
$list->each_index( sub { say "\$_=$_" } );

See List::Rubyish.

How can I get the current array index in a foreach loop?

based on @fabien-snauwaert's answer but simplified if you do not need the original key

$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {

    // display the current index +  value
    echo $index . ':' . $value;

    // first index
    if ( $index == 0 ) {
        echo ' -- This is the first element in the associative array';
    }

    // last index
    if ( $index == count( $array ) - 1 ) {
        echo ' -- This is the last element in the associative array';
    }
    echo '<br>';
}

Bash foreach loop

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

Javascript foreach loop on associative array object

This is very simple approach. The Advantage is you can get keys as well:

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

For ES6:

array.forEach(value => {
  console.log(value)
})  

For ES6: (If you want value, index and the array itself)

array.forEach((value, index, self) => {
  console.log(value, index, self)
})  

Unsetting array values in a foreach loop

$image is in your case the value of the item and not the key. Use the following syntax to get the key too:

foreach ($images as $key => $value) {
    /* … */
}

Now you can delete the item with unset($images[$key]).

Get loop counter/index using for…of syntax in JavaScript

For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

loop over an Array:

var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

loop over an Object:

var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

Is a LINQ statement faster than a 'foreach' loop?

LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.

With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat foreach, but most likely you wouldn't have done a blanket "select * from foo" anyway, so that isn't necessarily a fair comparison.

Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.

C#, Looping through dataset and show each record from a dataset column

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        var ParentId=dr["ParentId"].ToString();
    }
}

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

Get current index from foreach loop

You can't, because IEnumerable doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue elements (or long.MaxValue if you use a long index), you can:

  1. Don't use foreach, and use a for loop, converting your IEnumerable to a generic enumerable first:

    var genericList = list.Cast<object>();
    for(int i = 0; i < genericList.Count(); ++i)
    {
       var row = genericList.ElementAt(i);
       /* .... */
    }
    
  2. Have an external index:

    int i = 0;
    foreach(var row in list)
    {
       /* .... */
       ++i;
    }
    
  3. Get the index via Linq:

    foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
    {
      var row = rowObject.Row;
      var i = rowObject.Index;
      /* .... */    
    }
    

In your case, since your IEnumerable is not a generic one, I'd rather use the foreach with external index (second method)... otherwise, you may want to make the Cast<object> outside your loop to convert it to an IEnumerable<object>.

Your datatype is not clear from the question, but I'm assuming object since it's an items source (it could be DataGridRow)... you may want to check if it's directly convertible to a generic IEnumerable<object> without having to call Cast<object>(), but I'll make no such assumptions.


All this said:

The concept of an "index" is foreign to an IEnumerable. An IEnumerable can be potentially infinite. In your example, you are using the ItemsSource of a DataGrid, so more likely your IEnumerable is just a list of objects (or DataRows), with a finite (and hopefully less than int.MaxValue) number of members, but IEnumerable can represent anything that can be enumerated (and an enumeration can potentially never end).

Take this example:

public static IEnumerable InfiniteEnumerable()
{
  var rnd = new Random();
  while(true)
  {
    yield return rnd.Next();
  }
}

So if you do:

foreach(var row in InfiniteEnumerable())
{
  /* ... */
}

Your foreach will be infinite: if you used an int (or long) index, you'll eventually overflow it (and unless you use an unchecked context, it'll throw an exception if you keep adding to it: even if you used unchecked, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).

So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

Is there a way to avoid null check before the for-each loop iteration starts?

1) if list1 is a member of a class, create the list in the constructor so it's there and non-null though empty.

2) for (Object obj : list1 != null ? list1 : new ArrayList())

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

Laravel blade check empty foreach

I think you are trying to check whether the array is empty or not.You can do like this :

@if(!$result->isEmpty())
     // $result is not empty
@else
    // $result is empty
@endif

Reference isEmpty()

Node.js: for each … in not working

There's no for each in in the version of ECMAScript supported by Node.js, only supported by firefox currently.

The important thing to note is that JavaScript versions are only relevant to Gecko (Firefox's engine) and Rhino (which is always a few versions behind). Node uses V8 which follows ECMAScript specifications

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

You can also use CopyOnWriteArrayList instead of an ArrayList. This is the latest recommended approach by from JDK 1.5 onwards.

TypeScript for ... of with index / key?

.forEach already has this ability:

const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
});

But if you want the abilities of for...of, then you can map the array to the index and value:

for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
}

That's a little long, so it may help to put it in a reusable function:

function toEntries<T>(a: T[]) {
    return a.map((value, index) => [index, value] as const);
}

for (const [index, value] of toEntries(someArray)) {
    // ..etc..
}

Iterable Version

This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration compiler option.

function* toEntries<T>(values: T[] | IterableIterator<T>) {
    let index = 0;
    for (const value of values) {
        yield [index, value] as const;
        index++;
    }
}

Array.prototype.entries() - ES6+

If you are able to target ES6+ environments then you can use the .entries() method as outlined in Arnavion's answer.

Is there a 'foreach' function in Python 3?

Here is the example of the "foreach" construction with simultaneous access to the element indexes in Python:

for idx, val in enumerate([3, 4, 5]):
    print (idx, val)

break out of if and foreach

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$device = "wanted";
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;

        // will leave the foreach loop and also the if statement
        break;
        some_function(); // never reached!
    }
    another_function();  // not executed after match/break
}

Just for completeness for others that stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

foreach (array('1','2','3') as $a) {
    echo "$a ";
    foreach (array('3','2','1') as $b) {
        echo "$b ";
        if ($a == $b) { 
            break 2;  // this will break both foreach loops
        }
    }
    echo ". ";  // never reached!
}
echo "!";

Resulting output:

1 3 2 1 !

"for" vs "each" in Ruby

As far as I know, using blocks instead of in-language control structures is more idiomatic.

How do you remove an array element in a foreach loop?

A better solution is to use the array_filter function:

$display_related_tags =
    array_filter($display_related_tags, function($e) use($found_tag){
        return $e != $found_tag['name'];
    });

As the php documentation reads:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

endforeach in loops?

It's the end statement for the alternative syntax:

foreach ($foo as $bar) :
    ...
endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>
    <div ...>
        ...
    </div>
<?php endforeach; ?>

How to delete object from array inside foreach loop?

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

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Note that I prefer the code to be short.

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .ToList();

or with a simple foreach:

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
    if (item.Selected) selected.Add(item);

If you just want the ListItem.Value:

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .ToList();

How do you get the index of the current iteration of a foreach loop?

C# 7 finally gives us an elegant way to do this:

static class Extensions
{
    public static IEnumerable<(int, T)> Enumerate<T>(
        this IEnumerable<T> input,
        int start = 0
    )
    {
        int i = start;
        foreach (var t in input)
        {
            yield return (i++, t);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var s = new string[]
        {
            "Alpha",
            "Bravo",
            "Charlie",
            "Delta"
        };

        foreach (var (i, t) in s.Enumerate())
        {
            Console.WriteLine($"{i}: {t}");
        }
    }
}

PHP - Modify current object in foreach loop

There are 2 ways of doing this

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

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

or

foreach($questions as &$question){

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

Per the PHP foreach documentation:

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

Return from lambda forEach() in java

You can also throw an exception:

Note:

For the sake of readability each step of stream should be listed in new line.

players.stream()
       .filter(player -> player.getName().contains(name))
       .findFirst()
       .orElseThrow(MyCustomRuntimeException::new);

if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch and throwing these exceptions are for very special cases that you expect them and can be handled properly.)

Update all objects in a collection using LINQ

My 2 pennies:-

 collection.Count(v => (v.PropertyToUpdate = newValue) == null);

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Possible to iterate backwards through a foreach?

Sometimes you don't have the luxury of indexing, or perhaps you want to reverse the results of a Linq query, or maybe you don't want to modify the source collection, if any of these are true, Linq can help you.

A Linq extension method using anonymous types with Linq Select to provide a sorting key for Linq OrderByDescending;

    public static IEnumerable<T> Invert<T>(this IEnumerable<T> source)
    {
        var transform = source.Select(
            (o, i) => new
            {
                Index = i,
                Object = o
            });

        return transform.OrderByDescending(o => o.Index)
                        .Select(o => o.Object);
    }

Usage:

    var eable = new[]{ "a", "b", "c" };

    foreach(var o in eable.Invert())
    {
        Console.WriteLine(o);
    }

    // "c", "b", "a"

It is named "Invert" because it is synonymous with "Reverse" and enables disambiguation with the List Reverse implementation.

It is possible to reverse certain ranges of a collection too, since Int32.MinValue and Int32.MaxValue are out of the range of any kind of collection index, we can leverage them for the ordering process; if an element index is below the given range, it is assigned Int32.MaxValue so that its order doesn't change when using OrderByDescending, similarly, elements at an index greater than the given range, will be assigned Int32.MinValue, so that they appear to the end of the ordering process. All elements within the given range are assigned their normal index and are reversed accordingly.

    public static IEnumerable<T> Invert<T>(this IEnumerable<T> source, int index, int count)
    {
        var transform = source.Select(
            (o, i) => new
            {
                Index = i < index ? Int32.MaxValue : i >= index + count ? Int32.MinValue : i,
                Object = o
            });

        return transform.OrderByDescending(o => o.Index)
                        .Select(o => o.Object);
    }

Usage:

    var eable = new[]{ "a", "b", "c", "d" };

    foreach(var o in eable.Invert(1, 2))
    {
        Console.WriteLine(o);
    }

    // "a", "c", "b", "d"

I'm not sure of the performance hits of these Linq implementations versus using a temporary List to wrap a collection for reversing.


At time of writing, I was not aware of Linq's own Reverse implementation, still, it was fun working this out. https://msdn.microsoft.com/en-us/library/vstudio/bb358497(v=vs.100).aspx

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

PHP create key => value pairs within a foreach

Create key-value pairs within a foreach like this:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) {
        $offerArray[$key] = $value[4];
    }

    return $offerArray;
}

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>

or

$sidemenus = mysql_fetch_array($results);

then

<?php echo $sidemenu['mname']."<br />";?>

How do I apply the for-each loop to every character in a String?

You can also use a lambda in this case.

    String s = "xyz";
    IntStream.range(0, s.length()).forEach(i -> {
        char c = s.charAt(i);
    });

Advantages of std::for_each over for loop

The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled.

I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this

for(auto it = collection.begin(); it != collection.end() ; ++it)
{
   foo(*it);
}

Or this

for_each(collection.begin(), collection.end(), [](Element& e)
{
   foo(e);
});

when the range-based for loop syntax is available:

for(Element& e : collection)
{
   foo(e);
}

This kind of syntax has been available in Java and C# for some time now, and actually there are way more foreach loops than classical for loops in every recent Java or C# code I saw.

Using Python to execute a command on every file in a folder

Use os.walk to iterate recursively over directory content:

import os

root_dir = '.'

for directory, subdirectories, files in os.walk(root_dir):
    for file in files:
        print os.path.join(directory, file)

No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

Go to "next" iteration in JavaScript forEach loop

You can simply return if you want to skip the current iteration.

Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

Loop through all the rows of a temp table and call a stored procedure for each row

Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.

You may want to experiment with BulkCopy in your C# or VB.Net code.

PHP: Limit foreach() statement?

In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;
    }
}

foreach (limit($arr, 10) as $key => $value) {
    // do stuff
}

Generators rock.

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

Why am I not getting a java.util.ConcurrentModificationException in this example?

One way to handle it it to remove something from a copy of a Collection (not Collection itself), if applicable. Clone the original collection it to make a copy via a Constructor.

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For your specific case, first off, i don't think final is a way to go considering you intend to modify the list past declaration

private static final List<Integer> integerList;

Also consider modifying a copy instead of the original list.

List<Integer> copy = new ArrayList<Integer>(integerList);

for(Integer integer : integerList) {
    if(integer.equals(remove)) {                
        copy.remove(integer);
    }
}

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

How do I copy items from list to list without foreach?

This method will create a copy of your list but your type should be serializable.

Use:

List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList(); 

Method:

public static List<T> CopyList<T>(this List<T> lst)
    {
        List<T> lstCopy = new List<T>();
        foreach (var item in lst)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, item);
                stream.Position = 0;
                lstCopy.Add((T)formatter.Deserialize(stream));
            }
        }
        return lstCopy;
    }

Python foreach equivalent

For a dict we can use a for loop to iterate through the index, key and value:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##

What is the difference between for and foreach?

I'll tryto answer this in a more general approach:

foreach is used to iterate over each element of a given set or list (anything implementing IEnumerable) in a predefined manner. You can't influence the exact order (other than skipping entries or canceling the whole loop), as that's determined by the container.

foreach (String line in document) { // iterate through all elements of "document" as String objects
    Console.Write(line); // print the line
}

for is just another way to write a loop that has code executed before entering the loop and once after every iteration. It's usually used to loop through code a given number of times. Contrary to foreach here you're able to influence the current position.

for (int i = 0, j = 0; i < 100 && j < 10; ++i) { // set i and j to 0, then loop as long as i is less than 100 or j is less than 10 and increase i after each iteration
    if (i % 8 == 0) { // skip all numbers that can be divided by 8 and count them in j
        ++j
        continue;
    }
    Console.Write(i);
}
Console.Write(j);

If possible and applicable, always use foreach rather than for (assuming there's some array index). Depending on internal data organisation, foreach can be a lot faster than using for with an index (esp. when using linked lists).

Is there a foreach loop in Go?

I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:

package main

import (
    "fmt"

    col "github.com/jose78/go-collection/collections"
)

type user struct {
    name string
    age  int
    id   int
}

func main() {
    newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
    newList = append(newList, user{"Mon", 0, 3})

    newList.Foreach(simpleLoop)
    
    if err := newList.Foreach(simpleLoopWithError); err != nil{
        fmt.Printf("This error >>> %v <<< was produced", err )  
    }
}

var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
    fmt.Printf("%d.- item:%v\n", index, mapper)
}


var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
    if index > 1{
        panic(fmt.Sprintf("Error produced with index == %d\n", index))
    }
    fmt.Printf("%d.- item:%v\n", index, mapper)
}

The result of this execution should be:

0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2

ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
 <<< was produced

Try this code in playGrounD

Why is "forEach not a function" for this object?

When I tried to access the result from

Object.keys(a).forEach(function (key){ console.log(a[key]); });

it was plain text result with no key-value pairs Here is an example

var fruits = {
    apple: "fruits/apple.png",
    banana: "fruits/banana.png",
    watermelon: "watermelon.jpg",
    grapes: "grapes.png",
    orange: "orange.jpg"
}

Now i want to get all links in a separated array , but with this code

    function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
    console.log('\"'+obJect[x]+'\"');
});
}

the result of :

linksOfPics(fruits)



"fruits/apple.png"
 "fruits/banana.png"
 "watermelon.jpg"
 "grapes.png"
 "orange.jpg"
undefined

I figured out this one which solves what I'm looking for

  console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

Does C have a "foreach" loop construct?

C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...

foreach (Element element in collection)
{
}

... then the equivalent of this foreach statement in C might be be like:

for (
    Element* element = GetFirstElement(&collection);
    element != 0;
    element = GetNextElement(&collection, element)
    )
{
    //TODO: do something with this element instance ...
}

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

Break or return from Java 8 stream forEach?

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

Foreach loop, determine which is the last iteration of the loop

     List<int> ListInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


                int count = ListInt.Count;
                int index = 1;
                foreach (var item in ListInt)
                {
                    if (index != count)
                    {
                        Console.WriteLine("do something at index number  " + index);
                    }
                    else
                    {
                        Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
                    }
                    index++;

                }
 //OR
                int count = ListInt.Count;
                int index = 1;
                foreach (var item in ListInt)
                {
                    if (index < count)
                    {
                        Console.WriteLine("do something at index number  " + index);
                    }
                    else
                    {
                        Console.WriteLine("Foreach loop, this is the last iteration of the loop " + index);
                    }
                    index++;

                }

How to remove element from array in forEach loop?

Use Array.prototype.filter instead of forEach:

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);

How to 'foreach' a column in a DataTable using C#?

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

php foreach with multidimensional array

Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps

$response = array();    
foreach ($res as $result) {
        $elements = array("firstname" => $result[0], "subject_name" => $result[1]);
        array_push($response, $elements);
    }

How to check if variable is array?... or something array-like

<?php
$var = new ArrayIterator();

var_dump(is_array($var), ($var instanceof ArrayIterator));

returns bool(false) or bool(true)

Difference between "as $key => $value" and "as $value" in PHP foreach

if the array looks like:

  • $featured["fruit"] = "orange";
  • $featured["fruit"] = "banana";
  • $featured["vegetable"] = "carrot";

the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

JavaScript: Difference between .forEach() and .map()

Map implicitly returns while forEach does not.

This is why when you're coding a JSX application, you almost always use map instead of forEach to display content in React.

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

Two arrays in foreach loop

Walk it out...

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
  • PHP 5.3+

    array_walk($codes, function ($code,$key) use ($names) { 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    });
    
  • Before PHP 5.3

    array_walk($codes, function ($code,$key,$names){ 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    },$names);
    
  • or combine

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        echo '<option value="' . $code . '">' . $name . '</option>';
    })
    
  • in select

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        @$opts = '<option value="' . $code . '">' . $name . '</option>';
    })
    echo "<select>$opts</select>";
    

demo

For..In loops in JavaScript - key value pairs

var obj = {...};
for (var key in obj) {
    var value = obj[key];

}

The php syntax is just sugar.

How to find the foreach index?

I would like to add this, I used this in laravel to just index my table:

  • With $loop->index
  • I also preincrement it with ++$loop to start at 1

My Code:

@foreach($resultsPerCountry->first()->studies as $result)
  <tr>
    <td>{{ ++$loop->index}}</td>                                    
  </tr>
@endforeach

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

jquery loop on Json data using $.each

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});

$.each(data, function(i, item) {
    alert(item.PageName);
});

these two options work well, unless you have something like:

var data.result = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data.result, function(i, item) {
    alert(data.result[i].PageName);
});

EDIT:

try with this and describes what the result

$.get('/Cms/GetPages/123', function(data) {
  alert(data);
});

FOR EDIT 3:

this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.

$.get('/Cms/GetPages/123', function(data) {
  $.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
   alert(item.PageName);
  });
});

Short circuit Array.forEach like calling break

There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

_x000D_
_x000D_
var BreakException = {};_x000D_
_x000D_
try {_x000D_
  [1, 2, 3].forEach(function(el) {_x000D_
    console.log(el);_x000D_
    if (el === 2) throw BreakException;_x000D_
  });_x000D_
} catch (e) {_x000D_
  if (e !== BreakException) throw e;_x000D_
}
_x000D_
_x000D_
_x000D_

JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

Use Array#some

Instead, use Array#some:

_x000D_
_x000D_
[1, 2, 3].some(function(el) {_x000D_
  console.log(el);_x000D_
  return el === 2;_x000D_
});
_x000D_
_x000D_
_x000D_

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.

PHP foreach loop key value

As Pekka stated above

foreach ($array as $key => $value)

Also you might want to try a recursive function

displayRecursiveResults($site);

function displayRecursiveResults($arrayObject) {
    foreach($arrayObject as $key=>$data) {
        if(is_array($data)) {
            displayRecursiveResults($data);
        } elseif(is_object($data)) {
            displayRecursiveResults($data);
        } else {
            echo "Key: ".$key." Data: ".$data."<br />";
        }
    }
}

Sum values in foreach loop php

You can use array_sum().

$total = array_sum($group);

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

Can one do a for each loop in java in reverse order?

Definitely a late answer to this question. One possibility is to use the ListIterator in a for loop. It's not as clean as colon-syntax, but it works.

List<String> exampleList = new ArrayList<>();
exampleList.add("One");
exampleList.add("Two");
exampleList.add("Three");

//Forward iteration
for (String currentString : exampleList) {
    System.out.println(currentString); 
}

//Reverse iteration
for (ListIterator<String> itr = exampleList.listIterator(exampleList.size()); itr.hasPrevious(); /*no-op*/ ) {
    String currentString = itr.previous();
    System.out.println(currentString); 
}

Credit for the ListIterator syntax goes to "Ways to iterate over a list in Java"

Count number of iterations in a foreach loop

Try:

$counter = 0;
foreach ($Contents as $item) {
          something 
          your code  ...
      $counter++;      
}
$total_count=$counter-1;

Find the last element of an array while using a foreach loop in PHP

If I understand you, then all you need is to reverse the array and get the last element by a pop command:

   $rev_array = array_reverse($array);

   echo array_pop($rev_array);

PHP cURL custom headers

Here is one basic function:

/**
 * 
 * @param string $url
 * @param string|array $post_fields
 * @param array $headers
 * @return type
 */
function cUrlGetData($url, $post_fields = null, $headers = null) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($post_fields && !empty($post_fields)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    }
    if ($headers && !empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

Usage example:

$url = "http://www.myurl.com";
$post_fields = 'postvars=val1&postvars2=val2';
$headers = ['Content-Type' => 'application/x-www-form-urlencoded', 'charset' => 'utf-8'];
$dat = cUrlGetData($url, $post_fields, $headers);

Git - push current branch shortcut

You should take a look to a similar question in Default behavior of "git push" without a branch specified

Basically it explains how to set the default behavior to push your current branch just executing git push. Probably what you need is:

git config --global push.default current

Other options:

  • nothing : Do not push anything
  • matching : Push all matching branches
  • upstream/tracking : Push the current branch to whatever it is tracking
  • current : Push the current branch

Constructors in JavaScript objects

Yes, you can define a constructor inside a class declaration like this:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

What is dynamic programming?

The key bits of dynamic programming are "overlapping sub-problems" and "optimal substructure". These properties of a problem mean that an optimal solution is composed of the optimal solutions to its sub-problems. For instance, shortest path problems exhibit optimal substructure. The shortest path from A to C is the shortest path from A to some node B followed by the shortest path from that node B to C.

In greater detail, to solve a shortest-path problem you will:

  • find the distances from the starting node to every node touching it (say from A to B and C)
  • find the distances from those nodes to the nodes touching them (from B to D and E, and from C to E and F)
  • we now know the shortest path from A to E: it is the shortest sum of A-x and x-E for some node x that we have visited (either B or C)
  • repeat this process until we reach the final destination node

Because we are working bottom-up, we already have solutions to the sub-problems when it comes time to use them, by memoizing them.

Remember, dynamic programming problems must have both overlapping sub-problems, and optimal substructure. Generating the Fibonacci sequence is not a dynamic programming problem; it utilizes memoization because it has overlapping sub-problems, but it does not have optimal substructure (because there is no optimization problem involved).

How do I center align horizontal <UL> menu?

Here's a good article on how to do it in a pretty rock-solid way, without any hacks and full cross-browser support. Works for me:

--> http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Drawing a line/path on Google Maps

public class MainActivity extends FragmentActivity  {


  List<Overlay> mapOverlays;
  GeoPoint point1, point2;
  LocationManager locManager;
  Drawable drawable;
  Document document;
  GMapV2GetRouteDirection v2GetRouteDirection;
  LatLng fromPosition;
  LatLng toPosition;
  GoogleMap mGoogleMap;
  MarkerOptions markerOptions;
  Location location ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        v2GetRouteDirection = new GMapV2GetRouteDirection();
      SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
        mGoogleMap = supportMapFragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.getUiSettings().setCompassEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
        mGoogleMap.setTrafficEnabled(true);
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        markerOptions = new MarkerOptions();
        fromPosition = new LatLng(11.663837, 78.147297);
        toPosition = new LatLng(11.723512, 78.466287);
        GetRouteTask getRoute = new GetRouteTask();
        getRoute.execute();
  }
  /**
   *
   * @author VIJAYAKUMAR M
   * This class Get Route on the map
   *
   */
  private class GetRouteTask extends AsyncTask<String, Void, String> {

        private ProgressDialog Dialog;
        String response = "";
        @Override
        protected void onPreExecute() {
              Dialog = new ProgressDialog(MainActivity.this);
              Dialog.setMessage("Loading route...");
              Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
              //Get All Route values
                         document = v2GetRouteDirection.getDocument(fromPosition, toPosition,          GMapV2GetRouteDirection.MODE_DRIVING);
                    response = "Success";
              return response;

        }

        @Override
        protected void onPostExecute(String result) {
              mGoogleMap.clear();
              if(response.equalsIgnoreCase("Success")){
              ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
              PolylineOptions rectLine = new PolylineOptions().width(10).color(
                          Color.RED);

              for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));
              }
              // Adding route on the map
              mGoogleMap.addPolyline(rectLine);
              markerOptions.position(toPosition);
              markerOptions.draggable(true);
              mGoogleMap.addMarker(markerOptions);

              }

              Dialog.dismiss();
        }
  }
  @Override
  protected void onStop() {
        super.onStop();
        finish();
    }
 }

Route Helper class

 public class GMapV2GetRouteDirection {
  public final static String MODE_DRIVING = "driving";
  public final static String MODE_WALKING = "walking";

  public GMapV2GetRouteDirection() { }

  public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + start.latitude + "," + start.longitude 
            + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=driving";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }

  public String getDurationText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DurationText", node2.getTextContent());
    return node2.getTextContent();
 }

 public int getDurationValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getDistanceText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DistanceText", node2.getTextContent());
    return node2.getTextContent();
  }

  public int getDistanceValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DistanceValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getStartAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("start_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getEndAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("end_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getCopyRights (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("copyrights");
    Node node1 = nl1.item(0);
    Log.i("CopyRights", node1.getTextContent());
    return node1.getTextContent();
  }

   public ArrayList<LatLng> getDirection (Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for(int j = 0 ; j < arr.size() ; j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
 }

 private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
 }

 private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
  }
 }

#if DEBUG vs. Conditional("DEBUG")

Let's presume your code also had an #else statement which defined a null stub function, addressing one of Jon Skeet's points. There's a second important distinction between the two.

Suppose the #if DEBUG or Conditional function exists in a DLL which is referenced by your main project executable. Using the #if, the evaluation of the conditional will be performed with regard to the library's compilation settings. Using the Conditional attribute, the evaluation of the conditional will be performed with regard to the compilation settings of the invoker.

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

Best way to check for IE less than 9 in JavaScript without library

Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

You can then do:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

Getting a random value from a JavaScript array

Simple Function :

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

How to make an executable JAR file?

Here it is in one line:

jar cvfe myjar.jar package.MainClass *.class

where MainClass is the class with your main method, and package is MainClass's package.

Note you have to compile your .java files to .class files before doing this.

c  create new archive
v  generate verbose output on standard output
f  specify archive file name
e  specify application entry point for stand-alone application bundled into an executable jar file

This answer inspired by Powerslave's comment on another answer.

Where is git.exe located?

Here are step by step instructions for you to find out:

  1. If you're using any version of Windows, do Ctrl - Shift - Esc of open Task Manager.
  2. Open GitHub, and look into Task Manager.
  3. There should be something like this: What's in Task Manager when GitHub is open.
  4. Right click the row called GitHub, and select "Open file location".
  5. A window should pop up, showing you where the file is. Github.exe found!


There you go!

You can do this with any application, not just GitHub.

Sorting multiple keys with Unix sort

Use the -k option (or --key=POS1[,POS2]). It can appear multiple times and each key can have global options (such as n for numeric sort)

Find all elements on a page whose element ID contains a certain text using jQuery

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

How can I view the Git history in Visual Studio Code?

I recommend you this repository, https://github.com/DonJayamanne/gitHistoryVSCode

Git History Git History

It does exactly what you need and has these features:

  • View the details of a commit, such as author name, email, date, committer name, email, date and comments.
  • View a previous copy of the file or compare it against the local workspace version or a previous version.
  • View the changes to the active line in the editor (Git Blame).
  • Configure the information displayed in the list
  • Use keyboard shortcuts to view history of a file or line
  • View the Git log (along with details of a commit, such as author name, email, comments and file changes).

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

May be You are not registering the Controllers. Try below code:

Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder

  public class ControllerFactory :DefaultControllerFactory
    {
    protected override IController GetControllerInstance(RequestContext         requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format(
                        "Type requested is not a controller: {0}",
                        controllerType.Name),
                        "controllerType");

                return MvcUnityContainer.Container.Resolve(controllerType) as IController;
            }
            catch
            {
                return null;
            }

        }
        public static class MvcUnityContainer
        {
            public static UnityContainer Container { get; set; }
        }
    }

Step 2:Regigster it in BootStrap: inBuildUnityContainer method

private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>();    
      //RegisterTypes(container);
      container = new UnityContainer();
      container.RegisterType<IProductRepository, ProductRepository>();


      MvcUnityContainer.Container = container;
      return container;
    }

Step 3: In Global Asax.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            Bootstrapper.Initialise();
            ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));

        }

And you are done

Set background color of WPF Textbox in C# code

Have you taken a look at Color.FromRgb?

Cannot access wamp server on local network

If you are using wamp stack, it will be fixed by open port in Firewall (Control Pannel). It work for my case (detail how to open port 80: https://tips.alocentral.com/open-tcp-port-80-in-windows-firewall/)

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

Following steps solved the issue for me..

  • Copied the zip file into the Program Files folder and extracted to "apache-maven-3.6.3-bin".

  • Then copied the path, C:\Program Files\apache-maven-3.6.3-bin\apache-maven-3.6.3

  • Then created the new MAVEN_HOME variable within environmental variables with the above path.

Also added,

C:\Program Files\apache-maven-3.6.3-bin\apache-maven-3.6.3\bin

address to the "PATH" variable

How to do vlookup and fill down (like in Excel) in R?

I think you can also use match():

largetable$HouseTypeNo <- with(lookup,
                     HouseTypeNo[match(largetable$HouseType,
                                       HouseType)])

This still works if I scramble the order of lookup.

AWS Lambda import module error in python

My problem was that the .py file and dependencies were not in the zip's "root" directory. e.g the path of libraries and lambda function .py must be:

<lambda_function_name>.py
<name of library>/foo/bar/

not

/foo/bar/<name of library>/foo2/bar2

For example:

drwxr-xr-x  3.0 unx        0 bx stor 20-Apr-17 19:43 boto3/ec2/__pycache__/
-rw-r--r--  3.0 unx      192 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/__init__.cpython-37.pyc
-rw-r--r--  3.0 unx      758 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/deletetags.cpython-37.pyc
-rw-r--r--  3.0 unx      965 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/createtags.cpython-37.pyc
-rw-r--r--  3.0 unx     7781 tx defN 20-Apr-17 20:33 download-cs-sensors-to-s3.py

How to convert a Java 8 Stream to an Array?

Using the toArray(IntFunction<A[]> generator) method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.

However, if the returned array's type is not important, simply using the toArray() method is both easier and shorter. For example:

    Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
    System.out.printf("%s, %s, %s!", args.toArray());

How can I convert a date to GMT?

After searching for an hour or two ,I've found a simple solution below.

const date = new Date(`${date from client} GMT`);

inside double ticks, there is a date from client side plust GMT.

I'm first time commenting, constructive criticism will be welcomed.

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.

_x000D_
_x000D_
function isValidDate(dateString) {_x000D_
  var regEx = /^\d{4}-\d{2}-\d{2}$/;_x000D_
  if(!dateString.match(regEx)) return false;  // Invalid format_x000D_
  var d = new Date(dateString);_x000D_
  var dNum = d.getTime();_x000D_
  if(!dNum && dNum !== 0) return false; // NaN value, Invalid date_x000D_
  return d.toISOString().slice(0,10) === dateString;_x000D_
}_x000D_
_x000D_
_x000D_
/* Example Uses */_x000D_
console.log(isValidDate("0000-00-00"));  // false_x000D_
console.log(isValidDate("2015-01-40"));  // false_x000D_
console.log(isValidDate("2016-11-25"));  // true_x000D_
console.log(isValidDate("1970-01-01"));  // true = epoch_x000D_
console.log(isValidDate("2016-02-29"));  // true = leap day_x000D_
console.log(isValidDate("2013-02-29"));  // false = not leap day
_x000D_
_x000D_
_x000D_

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .lasttraces
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

Refresh certain row of UITableView based on Int in Swift

You can create an NSIndexPath using the row and section number then reload it like so:

let indexPath = NSIndexPath(forRow: rowNumber, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)

In this example, I've assumed that your table only has one section (i.e. 0) but you may change that value accordingly.

Update for Swift 3.0:

let indexPath = IndexPath(item: rowNumber, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)

SHA-256 or MD5 for file integrity

Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.

SHA256 takes somewhat more time to calculate than MD5, according to this answer.

Offhand, I'd say that MD5 would be probably be suitable for what you need.

How do I install TensorFlow's tensorboard?

If you're using the anaconda distribution of Python, then simply do:

 $? conda install -c conda-forge tensorboard 

or

 $? conda install -c anaconda tensorboard 

Also, you can have a look at various builds by search the packages repo by:

$? anaconda search -t conda tensorboard

which would list the channels and the corresponding builds, the supported OS, Python versions etc.,

Detecting arrow key presses in JavaScript

Possibly the tersest formulation:

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 38:
            alert('up');
            break;
        case 39:
            alert('right');
            break;
        case 40:
            alert('down');
            break;
    }
};

Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/

This should work cross-browser. Leave a comment if there is a browser where it does not work.

There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html. Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.

How to call javascript from a href?

I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" /> for this. That being said...

<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>

var clickHandler = function() {
     alert('Stuff happens now.');   
}


if (document.addEventListener) {
    document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
    document.getElementById('mylink').attachEvent('click', clickHandler);
}

http://jsfiddle.net/pDp4T/1/

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

How do I decrease the size of my sql server log file?

  1. Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.

  2. Use dbcc shrinkfile or Management Studio to shrink the log files.

Step #2 will do nothing until the backup mode is set.

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

simple Jquery hover enlarge

Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.

But your code is erroring out.. There seems to be an issue with the way you are using scale I got the jQuery to actually execute by changing your code to the following.

$(document).ready(function(){
    $('img').hover(function() {
        $(this).css("cursor", "pointer");
        $(this).toggle({
          effect: "scale",
          percent: "90%"
        },200);
    }, function() {
         $(this).toggle({
           effect: "scale",
           percent: "80%"
         },200);

    });
});  

But I have always done it by using CSS to setup my scaling and transition..

Here is an example, hopefully it helps.

$(document).ready(function(){
    $('#content').hover(function() {
        $("#content").addClass('transition');

    }, function() {
        $("#content").removeClass('transition');
    });
});

http://jsfiddle.net/y4yAP/

Locate current file in IntelliJ

In Intellij Idea Community edition 2020.1 :

  1. Right click on project header
  2. Select 'Always Select Opened File'

enter image description here

Android - Pulling SQlite database android device

Alternatively you can use my library Ultra Debugger. It's allow to download database as file or edit values directly in browser. No root needed, very easy to use.

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

How to generate a random string in Ruby

Array.new(n){[*"0".."9"].sample}.join, where n=8 in your case.

Generalized: Array.new(n){[*"A".."Z", *"0".."9"].sample}.join, etc.

From: "Generate pseudo random string A-Z, 0-9".

Does Index of Array Exist

You can use the length of the array, and see if your arbitrary number fits in that range. For example, if you have an array of size 10, then array[25] isn't valid because 25 is not less than 10.

Processing $http response in service

Here is a Plunk that does what you want: http://plnkr.co/edit/TTlbSv?p=preview

The idea is that you work with promises directly and their "then" functions to manipulate and access the asynchronously returned responses.

app.factory('myService', function($http) {
  var myService = {
    async: function() {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get('test.json').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  myService.async().then(function(d) {
    $scope.data = d;
  });
});

Here is a slightly more complicated version that caches the request so you only make it first time (http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview):

app.factory('myService', function($http) {
  var promise;
  var myService = {
    async: function() {
      if ( !promise ) {
        // $http returns a promise, which has a then function, which also returns a promise
        promise = $http.get('test.json').then(function (response) {
          // The then function here is an opportunity to modify the response
          console.log(response);
          // The return value gets picked up by the then in the controller.
          return response.data;
        });
      }
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  $scope.clearData = function() {
    $scope.data = {};
  };
  $scope.getData = function() {
    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
      $scope.data = d;
    });
  };
});

jquery animate .css

You can actually still use ".css" and apply css transitions to the div being affected. So continue using ".css" and add the below styles to your stylesheet for "#hfont1". Since ".css" allows for a lot more properties than ".animate", this is always my preferred method.

#hfont1 {
    -webkit-transition: width 0.4s;
    transition: width 0.4s;
}

Convert an int to ASCII character

This is how I converted a number to an ASCII code. 0 though 9 in hex code is 0x30-0x39. 6 would be 0x36.

unsigned int temp = 6;
or you can use unsigned char temp = 6;
unsigned char num;
 num = 0x30| temp;

this will give you the ASCII value for 6. You do the same for 0 - 9

to convert ASCII to a numeric value I came up with this code.

unsigned char num,code;
code = 0x39; // ASCII Code for 9 in Hex
num = 0&0F & code;

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

How to ensure a <select> form field is submitted when it is disabled?

Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

python: how to send mail with TO, CC and BCC?

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they


# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = [email protected]

Or

msg = "From: [email protected]" +
      "To: [email protected]" +
      "BCC: [email protected]" +
      "Subject: You've got mail!" +
      "This is the message body"

The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you'll need to import a class from email.message instead of merely passing strings into sendmail.

How to use a class object in C++ as a function parameter

If you want to pass class instances (objects), you either use

 void function(const MyClass& object){
   // do something with object  
 }

or

 void process(MyClass& object_to_be_changed){
   // change member variables  
 }

On the other hand if you want to "pass" the class itself

template<class AnyClass>
void function_taking_class(){
   // use static functions of AnyClass
   AnyClass::count_instances();
   // or create an object of AnyClass and use it
   AnyClass object;
   object.member = value;
}
// call it as 
function_taking_class<MyClass>();
// or 
function_taking_class<MyStruct>();

with

class MyClass{
  int member;
  //...
};
MyClass object1;

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

select the TOP N rows from a table

From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:

https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#using-offset-and-fetch-to-limit-the-rows-returned

Your query become:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS  
FETCH NEXT 20 ROWS ONLY;  

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

JavaScript moving element in the DOM

Sorry for bumping this thread I stumbled over the "swap DOM-elements" problem and played around a bit

The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)

The Code:

$('#element1').insertAfter($('#element2'));

The jQuery documentation says that insertAfter() moves the element and doesn't clone it

How to check if one DateTime is greater than the other in C#

if (StartDate>=EndDate)
{
    throw new InvalidOperationException("Ack!  StartDate is not before EndDate!");
}

How to insert data using wpdb

$wpdb->query("insert into ".$table_name." (name, email, country, country, course, message, datesent) values ('$name','$email', '$phone', '$country', '$course', '$message', )");

How do you initialise a dynamic array in C++?

Two ways:

char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset

Or:

std::vector<char> c(length, INITIAL_VALUE);

In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

std::vector<char> c(length);

[Edit: go vote for Fred's answer, char* c = new char[length]();]

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:

var value = ($("#text").val()).replace(".", ":");

Python: Removing spaces from list objects

result = map(str.strip, hello)

ngOnInit not being called when Injectable class is Instantiated

Note: this answer applies only to Angular components and directives, NOT services.

I had this same issue when ngOnInit (and other lifecycle hooks) were not firing for my components, and most searches led me here.

The issue is that I was using the arrow function syntax (=>) like this:

class MyComponent implements OnInit {
    // Bad: do not use arrow function
    public ngOnInit = () => {
        console.log("ngOnInit");
    }
}

Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:

class MyComponent implements OnInit {
    public ngOnInit() {
        console.log("ngOnInit");
    }
}

Multiplying Two Columns in SQL Server

In a query you can just do something like:

SELECT ColumnA * ColumnB FROM table

or

SELECT ColumnA - ColumnB FROM table

You can also create computed columns in your table where you can permanently use your formula.

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

Where does forever store console.log output?

if you run the command "forever logs", you can see where are the logs files.

Source: https://github.com/foreverjs/forever

What should be in my .gitignore for an Android Studio project?

There is NO NEED to add to the source control any of the following:

.idea/
.gradle/
*.iml
build/
local.properties

So you can configure hgignore or gitignore accordingly.

The first time a developer clones the source control can go:

  1. Open Android Studio
  2. Import Project
  3. Browse for the build.gradle within the cloned repository and open it

That's all

PS: Android Studio will then, through maven, get the gradle plugin assuming that your build.gradle looks similar to this:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

Android studio will generate the content of .idea folder (including the workspace.xml, which shouldn't be in source control because it is generated) and the .gradle folder.

This approach is Eclipse-friendly in the way that the source control does not really know anything about Android Studio. Android Studio just needs the build.gradle to import a project and generate the rest.

Nested JSON: How to add (push) new items to an object?

If your JSON is without key you can do it like this:

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

So, try this:

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

Then:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

How to plot ROC curve in Python

There is a library called metriculous that will do that for you:

$ pip install metriculous

Let's first mock some data, this would usually come from the test dataset and the model(s):

import numpy as np

def normalize(array2d: np.ndarray) -> np.ndarray:
    return array2d / array2d.sum(axis=1, keepdims=True)

class_names = ["Cat", "Dog", "Pig"]
num_classes = len(class_names)
num_samples = 500

# Mock ground truth
ground_truth = np.random.choice(range(num_classes), size=num_samples, p=[0.5, 0.4, 0.1])

# Mock model predictions
perfect_model = np.eye(num_classes)[ground_truth]
noisy_model = normalize(
    perfect_model + 2 * np.random.random((num_samples, num_classes))
)
random_model = normalize(np.random.random((num_samples, num_classes)))

Now we can use metriculous to generate a table with various metrics and diagrams, including ROC curves:

import metriculous

metriculous.compare_classifiers(
    ground_truth=ground_truth,
    model_predictions=[perfect_model, noisy_model, random_model],
    model_names=["Perfect Model", "Noisy Model", "Random Model"],
    class_names=class_names,
    one_vs_all_figures=True, # This line is important to include ROC curves in the output
).save_html("model_comparison.html").display()

The ROC curves in the output: metriculous ROC curves

The plots are zoomable and draggable, and you get further details when hovering with your mouse over the plot:

metriculous ROC curve

What's the quickest way to multiply multiple cells by another number?

Select Product from formula bar in your answer cell.

Select cells you want to multiply.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

         ` Adding the following to pom.xml will resolve the issue.      <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
   </pluginRepositories>
    
   <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
   </repositories>   `

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

You get this error if you have service A that depends on a static property / method of service B and the service B itself depends on service A trough dependency injection. So it's a kind of a circular dependency, although it isn't since the property / method is static. Probably a bug that occurs in combination with AOT.

Android soft keyboard covers EditText field

Edit your AndroidManifest.xml

android:windowSoftInputMode="adjustResize"

Add this to your root view of Layout file.

android:fitsSystemWindows="true"

That's all.

javac: invalid target release: 1.8

Your javac is not pointing to correct java.

Check where your javac is pointing using following command -

update-alternatives --config javac

If it is not pointed to the javac you want to compile with, point it to "/JAVA8_HOME/bin/javac", or which ever java you want to compile with.

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

Google Map API v3 ~ Simply Close an infowindow?

infowindow.open(null,null);

will close opened infowindow. It will work same as

Get first day of week in PHP?

How about this?

$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));

Git workflow and rebase vs merge questions

From what I have observed, git merge tends to keep the branches separate even after merging, whereas rebase then merge combines it into one single branch. The latter comes out much cleaner, whereas in the former, it would be easier to find out which commits belong to which branch even after merging.

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Creating instance list of different objects

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

objects list will accept any of the Object

You could design like as follows

public class BaseEmployee{/* stuffs */}

public class RegularEmployee extends BaseEmployee{/* stuffs */}

public class Contractors extends BaseEmployee{/* stuffs */}

and in list

List<? extends BaseEmployee> employeeList = new ArrayList<? extends BaseEmployee>();

Concatenate string with field value in MySQL

Have you tried using the concat() function?

ON tableTwo.query = concat('category_id=',tableOne.category_id)

What's the difference between isset() and array_key_exists()?

Complementing (as an algebraic curiosity) the @deceze answer with the @ operator, and indicating cases where is "better" to use @ ... Not really better if you need (no log and) micro-performance optimization:

  • array_key_exists: is true if a key exists in an array;
  • isset: is true if the key/variable exists and is not null [faster than array_key_exists];
  • @$array['key']: is true if the key/variable exists and is not (null or '' or 0); [so much slower?]
$a = array('k1' => 'HELLO', 'k2' => null, 'k3' => '', 'k4' => 0);

print isset($a['k1'])? "OK $a[k1].": 'NO VALUE.';            // OK
print array_key_exists('k1', $a)? "OK $a[k1].": 'NO VALUE.'; // OK
print @$a['k1']? "OK $a[k1].": 'NO VALUE.';                  // OK
// outputs OK HELLO.  OK HELLO. OK HELLO.

print isset($a['k2'])? "OK $a[k2].": 'NO VALUE.';            // NO
print array_key_exists('k2', $a)? "OK $a[k2].": 'NO VALUE.'; // OK
print @$a['k2']? "OK $a[k2].": 'NO VALUE.';                  // NO
// outputs NO VALUE.  OK .  NO VALUE.

print isset($a['k3'])? "OK $a[k3].": 'NO VALUE.';            // OK
print array_key_exists('k3', $a)? "OK $a[k3].": 'NO VALUE.'; // OK
print @$a['k3']? "OK $a[k3].": 'NO VALUE.';                  // NO
// outputs OK . OK . NO VALUE.

print isset($a['k4'])? "OK $a[k4].": 'NO VALUE.';            // OK
print array_key_exists('k4', $a)? "OK $a[k4].": 'NO VALUE.'; // OK
print @$a['k4']? "OK $a[k4].": 'NO VALUE.';                  // NO
// outputs OK 0. OK 0. NO VALUE

PS: you can change/correct/complement this text, it is a Wiki.

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

MySQL JOIN with LIMIT 1 on joined table

I would try something like this:

SELECT C.*,
      (SELECT P.id, P.title 
       FROM products as P
       WHERE P.category_id = C.id
       LIMIT 1)
FROM categories C

Calendar Recurring/Repeating Events - Best Storage Method

While the proposed solutions work, I was trying to implement with Full Calendar and it would require over 90 database calls for each view (as it loads current, previous, and next month), which, I wasn't too thrilled about.

I found an recursion library https://github.com/tplaner/When where you simply store the rules in the database and one query to pull all the relevant rules.

Hopefully this will help someone else, as I spent so many hours trying to find a good solution.

Edit: This Library is for PHP

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

Detect iPhone/iPad purely by css

iPhone & iPod touch:

<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />

iPhone 4 & iPod touch 4G:

<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />

iPad:

<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

This is the only command that worked for me. (I got it from M 8.0 documentation)

ALTER USER 'root'@'*' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';

How do I Search/Find and Replace in a standard string?

// Replace all occurrences of searchStr in str with replacer
// Each match is replaced only once to prevent an infinite loop
// The algorithm iterates once over the input and only concatenates 
// to the output, so it should be reasonably efficient
std::string replace(const std::string& str, const std::string& searchStr, 
    const std::string& replacer)
{
    // Prevent an infinite loop if the input is empty
    if (searchStr == "") {
        return str;
    }

    std::string result = "";
    size_t pos = 0;
    size_t pos2 = str.find(searchStr, pos);

    while (pos2 != std::string::npos) {
        result += str.substr(pos, pos2-pos) + replacer;
        pos = pos2 + searchStr.length();
        pos2 = str.find(searchStr, pos);
    }

    result += str.substr(pos, str.length()-pos);
    return result;
}

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

Jackson enum Serializing and DeSerializer

Besides using @JsonSerialize @JsonDeserialize, you can also use SerializationFeature and DeserializationFeature (jackson binding) in the object mapper.

Such as DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, which give default enum type if the one provided is not defined in the enum class.

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

After installing Microsoft.Web.Infrastructure through Nuget-Package Manager

PM> Install-Package Microsoft.Web.Infrastructure

Copy the Microsoft.Web.Infrastructure.dll manually from the Nuget-Package folder on your web application and then paste it in your bin folder of your web application deployed on the web server.

packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll

It worked for me.

Android design support library for API 28 (P) not working

Android documentation is clear on this.Go to the below page.Underneath,there are two columns with names "OLD BUILD ARTIFACT" and "AndroidX build artifact"

https://developer.android.com/jetpack/androidx/migrate

Now you have many dependencies in gradle.Just match those with Androidx build artifacts and replace them in the gradle.

That won't be enough.

Go to your MainActivity (repeat this for all activities) and remove the word AppCompact Activity in the statement "public class MainActivity extends AppCompatActivity " and write the same word again.But this time androidx library gets imported.Until now appcompact support file got imported and used (also, remove that appcompact import statement).

Also,go to your layout file. Suppose you have a constraint layout,then you can notice that the first line constraint layout in xml file have something related to appcompact.So just delete it and write Constraint layout again.But now androidx related constraint layout gets added.

repeat this for as many activities and as many xml layout files..

But don't worry: Android Studio displays all such possible errors while compiling.

CSS: Control space between bullet and <li>

It seems you can (somewhat) control the spacing using padding on the <li> tag.

<style type="text/css">
    li { padding-left: 10px; }
</style>

The catch is that it doesn't seem to allow you to scrunch it way-snug like your final example.

For that you could try turning off list-style-type and using &bull;

<ul style="list-style-type: none;">
    <li>&bull;Some list text goes here.</li>
</ul>

Returning Promises from Vuex actions

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

actions: {
    myAction(context, data) {
        return new Promise((resolve, reject) => {
            // Do something here... lets say, a http call using vue-resource
            this.$http("/api/something").then(response => {
                // http success, call the mutator and change something in state
                resolve(response);  // Let the calling function know that http is done. You may send some data back
            }, error => {
                // http failed, let the calling function know that action did not work out
                reject(error);
            })
        })
    }
}

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

export default {
    mounted: function() {
        // This component just got created. Lets fetch some data here using an action
        this.$store.dispatch("myAction").then(response => {
            console.log("Got some data, now lets show something in this component")
        }, error => {
            console.error("Got nothing from server. Prompt user to check internet connection and try again")
        })
    }
}

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

Edit: My views on the Vuex cycle of uni-directional data flow:

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

The promise from action is only to let the component know that action is complete.

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

Uncaught TypeError: Cannot read property 'length' of undefined

You are not passing the variable correctly. One fast solution is to make a global variable like this:

var global_json_data;
$(document).ready(function() {
    var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
    var string_data ="";
    var json_data = $.ajax({
        dataType: 'json', // Return JSON
        url: json_source,
        success: function(data){
            var data_obj = [];
            for (i=0; i<data.feed.entry.length; i++){
                var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
                data_obj.push(el)};

            console.log("data grabbed");  
            global_json_data =   data_obj;

            return data_obj;


        },      

        error: function(jqXHR, textStatus, errorThrown){ 
                        $('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    }); 

    $(':submit').click(function(event){
        var json_data = global_json_data;
        event.preventDefault();
        console.log(json_data.length);

        //function
        if ($('#place').val() !=''){
            var copy_string = $('#place').val();
            var converted_string = copy_string;
            for (i=0; i<json_data.length; i++){
                //console_log(data.feed.entry[i].title['$t']);
                converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'], 
                    '<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
            }  
            $('#results_box').text(converted_string).html();
        }
    });

});//document ready end 

Detect if PHP session exists

Which method is used to check if SESSION exists or not? Answer:

isset($_SESSION['variable_name'])

Example:

isset($_SESSION['id'])

How to open a new file in vim in a new window

If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.

to do this you can write: gVim --remote-tab-silent file

You could always make an alias to this command so that you don't have to type so many words. For example I use linux and bash and in my ~/.bashrc file I have:

alias g='gvim --remote-tab-silent'

so instead of doing $ mate file I do: $ g file

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.

//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events

ComboBox combobox2 = ManagerControl.myComboBox2;
...some events

.

//method in constructor
public static void InitializeDynamicControls()
{
     ComboBox cb = new ComboBox();
     cb.Background = new SolidColorBrush(Colors.Blue);
     ...
     cb.Width = 100;
     cb.Text = "Select window";
        
     ManagerControls.myCombobox1 = cb;
     ManagerControls.myComboBox2 = cb; // <-- error here
}

Solution: create another ComboBox cb2 and assign it to ManagerControls.myComboBox2.

I hope I helped someone.

How to pass extra variables in URL with WordPress

<?php
$edit_post = add_query_arg('c', '123', 'news' );

?>

<a href="<?php echo $edit_post; ?>">Go to New page</a>

You can add any page inplace of "news".

C++ vector of char array

You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.

If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct:

struct S {
  char a[10];
};

and then create a vector of structs:

vector <S> v;
S s;
s.a[0] = 'x';
v.push_back( s );

SQL Server String Concatenation with Null

This example will help you to handle various types while creating insert statements

select 
'insert into doc(Id, CDate, Str, Code, Price, Tag )' + 
'values(' +
      '''' + convert(nvarchar(50), Id) + ''',' -- uniqueidentifier
    + '''' + LEFT(CONVERT(VARCHAR, CDate, 120), 10) + ''',' -- date
    + '''' + Str+ ''',' -- string
    + '''' + convert(nvarchar(50), Code)  + ''',' -- int
    + convert(nvarchar(50), Price) + ',' -- decimal
    + '''' + ISNULL(Tag, '''''') + '''' + ')'  -- nullable string

 from doc
 where CDate> '2019-01-01 00:00:00.000'

MySQL INSERT INTO ... VALUES and SELECT

INSERT INTO table1 
SELECT "A string", 5, idTable2
FROM table2
WHERE ...

See: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html

Getting current date and time in JavaScript

This should do the trick:

function dateToString(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
    dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
    dateOfString += date.getFullYear();
    return dateOfString;
}

var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":"
            + currentdate.getSeconds();

Disabling submit button until all fields have values

Built upon rsplak's answer. It uses jQuery's newer .on() instead of the deprecated .bind(). In addition to input, it will also work for select and other html elements. It will also disable the submit button if one of the fields becomes blank again.

var fields = "#user_input, #pass_input, #v_pass_input, #email";

$(fields).on('change', function() {
    if (allFilled()) {
        $('#register').removeAttr('disabled');
    } else {
        $('#register').attr('disabled', 'disabled');
    }
});

function allFilled() {
    var filled = true;
    $(fields).each(function() {
        if ($(this).val() == '') {
            filled = false;
        }
    });
    return filled;
}

Demo: JSFiddle

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

I know this is buried, but I had caused this issue when I moved a database without giving the NT Service\MSQLSERVER account rights to the directory I moved the database files to. Giving the rights and restarting SQLServer did the trick.

Gradle, Android and the ANDROID_HOME SDK location

That question is from November 2013 (while Android Studio was still in Developer Preview mode),

Currently (AS v2.2, Aug-2016) during instalation AS asks to choose the SDK folder (or install on their default) and it automatically applies to which ever project you're opening.

That means any possible workaround or fix is irrelevant as the issue is not reproducible anymore.

How to AUTO_INCREMENT in db2?

You will have to create an auto-increment field with the sequence object (this object generates a number sequence).

Use the following CREATE SEQUENCE syntax:

  CREATE SEQUENCE seq_person
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 10

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):

  INSERT INTO Persons (P_Id,FirstName,LastName)
  VALUES (seq_person.nextval,'Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

MVC3 DropDownListFor - a simple example?

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

Vue template or render function not defined yet I am using neither?

I had this script in app.js in laravel which automatically adds all components in the component folder.

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))

To make it work just add default

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Undefined function mysql_connect()

There must be some syntax error. Copy/paste this code and see if it works:

<?php
    $link = mysql_connect('localhost', 'root', '');
    if (!$link) {
        die('Could not connect:' . mysql_error());
    }
    echo 'Connected successfully';
    ?

I had the same error message. It turns out I was using the msql_connect() function instead of mysql_connect().

Logging best practices

We use log4net on our web applications.

It's ability to customize logging at run-time by changing the XML configuration file is very handy when an application is malfunctioning at run-time and you need to see more information.

It also allows you to target specific classes or attributes to log under. This is very handy when you have an idea where the error is occurring. A classic example is NHibernate where you want to see just the SQL going to the database.

Edit:

We write all events to a database and the Trace system. The event log we use for errors or exceptions. We log most events to a database so that we can create custom reports and let the users view the log if they want to right from the application.

What's the difference between tilde(~) and caret(^) in package.json?

semver is separate in to 3 major sections which is broken by dots.

major.minor.patch
1.0.0

These different major, minor and patch are using to identify different releases. tide (~) and caret (^) are using to identify which minor and patch version to be used in package versioning.

~1.0.1
 Install 1.0.1 or **latest patch versions** such as 1.0.2 ,1.0.5
^1.0.1
 Install 1.0.1 or **latest patch and minor versions** such as 1.0.2 ,1.1.0 ,1.1.1

AngularJS $http, CORS and http authentication

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

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

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

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


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

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

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


});

MySQL search and replace some text in a field

The Replace string function will do that.

Check if number is decimal

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}

What's wrong with foreign keys?

I can see a few reasons to use foreign keys (Orphaned rows, as someone mentioned, are annoying) but I never use them either. With a relatively sane DB schema, I don't think they are 100% needed. Constraints are good, but enforcing them via software is a better method, I think.

Alex

How do I get into a non-password protected Java keystore or change the password?

Mac Mountain Lion has the same password now it uses Oracle.

How to push object into an array using AngularJS

Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview

Controller-

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

app.controller('TestController', function($scope) {
    this.arrayText = [{text:'Hello',},{text: 'world'}];

    this.addText = function(text) {

      if(text) {
        var obj = {
          text: text
        };
          this.arrayText.push(obj);
          this.myText = '';
          console.log(this.arrayText);
        }
      } 
 });

HTML

<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
        <input type="text" ng-model="testCtrl.myText" value="Lets go">
        <button type="submit">Add</button>
        <div ng-repeat="item in testCtrl.arrayText">
            <span>{{item}}</span>
        </div>
</form>

How can I stop a While loop?

The is operator in Python probably doesn't do what you expect. Instead of this:

    if numpy.array_equal(tmp,universe_array) is True:
        break

I would write it like this:

    if numpy.array_equal(tmp,universe_array):
        break

The is operator tests object identity, which is something quite different from equality.

CSV new-line character seen in unquoted field error

If this happens to you on mac (as it did to me):

  1. Save the file as CSV (MS-DOS Comma-Separated)
  2. Run the following script

    with open(csv_filename, 'rU') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            print ', '.join(row)
    

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Increasing the JVM maximum heap size for memory intensive applications

32-bit Java is limited to approximately 1.4 to 1.6 GB.

Oracle 32 bit heap FAQ

Quote

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Adding images to an HTML document with javascript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

_x000D_
_x000D_
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
_x000D_
_x000D_

... you'd get this:

enter image description here

How do I get indices of N maximum values in a NumPy array?

Use:

from operator import itemgetter
from heapq import nlargest
result = nlargest(N, enumerate(your_list), itemgetter(1))

Now the result list would contain N tuples (index, value) where value is maximized.

How to split a string, but also keep the delimiters?

If you want keep character then use split method with loophole in .split() method.

See this example:

public class SplitExample {


    public static void main(String[] args) {  
        String str = "Javathomettt";  
        System.out.println("method 1");
        System.out.println("Returning words:");  
        String[] arr = str.split("t", 40);  
        for (String w : arr) {  
            System.out.println(w+"t");  
        }  
        System.out.println("Split array length: "+arr.length);  
        System.out.println("method 2");
        System.out.println(str.replaceAll("t", "\n"+"t"));
    }

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

Detect if the device is iPhone X

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)

How to make overlay control above all other controls?

If you are using a Canvas or Grid in your layout, give the control to be put on top a higher ZIndex.

From MSDN:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="ZIndex Sample">
  <Canvas>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>
    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>

    <!-- Reverse the order to illustrate z-index property -->

    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>
  </Canvas>
</Page>

If you don't specify ZIndex, the children of a panel are rendered in the order they are specified (i.e. last one on top).

If you are looking to do something more complicated, you can look at how ChildWindow is implemented in Silverlight. It overlays a semitransparent background and popup over your entire RootVisual.

HashMap - getting First Key value

Note that you should note that your logic flow must never rely on accessing the HashMap elements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

Back to the post, you already did half the job by loading the first element key:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key) to get the respective value:

Object myValue = statusName.get(myKey);

How to split a dataframe string column into two columns?

I prefer exporting the corresponding pandas series (i.e. the columns I need), using the apply function to split the column content into multiple series and then join the generated columns to the existing DataFrame. Of course, the source column should be removed.

e.g.

 col1 = df["<col_name>"].apply(<function>)
 col2 = ...
 df = df.join(col1.to_frame(name="<name1>"))
 df = df.join(col2.toframe(name="<name2>"))
 df = df.drop(["<col_name>"], axis=1)

To split two words strings function should be something like that:

lambda x: x.split(" ")[0] # for the first element
lambda x: x.split(" ")[-1] # for the last element

Android: keeping a background service alive (preventing process death)

As Dave already pointed out, you could run your Service with foreground priority. But this practice should only be used when it's absolutely necessary, i.e. when it would cause a bad user experience if the Service got killed by Android. This is what the "foreground" really means: Your app is somehow in the foreground and the user would notice it immediately if it's killed (e.g. because it played a song or a video).

In most cases, requesting foreground priority for your Service is contraproductive!

Why is that? When Android decides to kill a Service, it does so because it's short of resources (usually RAM). Based on the different priority classes, Android decides which running processes, and this included services, to terminate in order to free resources. This is a healthy process that you want to happen so that the user has a smooth experience. If you request foreground priority, without a good reason, just to keep your service from being killed, it will most likely cause a bad user experience. Or can you guarantee that your service stays within a minimal resource consumption and has no memory leaks?1

Android provides sticky services to mark services that should be restarted after some grace period if they got killed. This restart usually happens within a few seconds.

Image you want to write an XMPP client for Android. Should you request foreground priority for the Service which contains your XMPP connection? Definitely no, there is absolutely no reason to do so. But you want to use START_STICKY as return flag for your service's onStartCommand method. So that your service is stopped when there is resource pressure and restarted once the situation is back to normal.

1: I am pretty sure that many Android apps have memory leaks. It something the casual (desktop) programmer doesn't care that much about.

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

Is there a way to make HTML5 video fullscreen?

No, it is not possible to have fullscreen video in html 5. If you want to know reasons, you're lucky because the argument battle for fullscreen is fought right now. See WHATWG mailing list and look for the word "video". I personally hope that they provide fullscreen API in HTML 5.

Where does npm install packages?

The easiest way would be to do

npm list -g

to list the package and view their installed location.

I had installed npm via chololatey, so the location is

C:\MyProgramData\chocolatey\lib\nodejs.commandline.0.10.31\tools\node_modules

C:\MyProgramData\ is chocolatey repo location.

Download history stock prices automatically from yahoo finance in python

When you're going to work with such time series in Python, pandas is indispensable. And here's the good news: it comes with a historical data downloader for Yahoo: pandas.io.data.DataReader.

from pandas.io.data import DataReader
from datetime import datetime

ibm = DataReader('IBM',  'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
print(ibm['Adj Close'])

Here's an example from the pandas documentation.

Update for pandas >= 0.19:

The pandas.io.data module has been removed from pandas>=0.19 onwards. Instead, you should use the separate pandas-datareader package. Install with:

pip install pandas-datareader

And then you can do this in Python:

import pandas_datareader as pdr
from datetime import datetime

ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
print(ibm['Adj Close'])

Downloading from Google Finance is also supported.

There's more in the documentation of pandas-datareader.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Why maven? What are the benefits?

Maven can provide benefits for your build process by employing standard conventions and practices to accelerate your development cycle while at the same time helping you achieve a higher rate of success. For a more detailed look at how Maven can help you with your development process please refer to The Benefits of Using Maven.

How can I install a local gem?

Well, it's this my DRY installation:

  1. Look into a computer with already installed gems needed in the cache directory (by default: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  2. Copy all "*.gems files" to a computer without gems in own gem cache place (by default the same patron path of first step: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  3. In the console be located in the gems cache (cd [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache) and fire the gem install anygemwithdependencieshere (by example cucumber-2.99.0)

It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)

Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command gem server and add the localhost url in gem sources, more information in: https://guides.rubygems.org/run-your-own-gem-server/

jquery how to empty input field

Since you are using jQuery, how about using a trigger-reset:

$(document).ready(function(){
  $('#shares').trigger(':reset');
});

Calculate business days

For holidays, make an array of days in some format that date() can produce. Example:

// I know, these aren't holidays
$holidays = array(
    'Jan 2',
    'Feb 3',
    'Mar 5',
    'Apr 7',
    // ...
);

Then use the in_array() and date() functions to check if the timestamp represents a holiday:

$day_of_year = date('M j', $timestamp);
$is_holiday = in_array($day_of_year, $holidays);

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

MacOSX homebrew mysql root password

Use init file to start mysql to change the root password.

brew services stop mysql
pkill mysqld
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'newRootPass';" > /tmp/mysql-init
$(brew --prefix mysql)/bin/mysqld --init-file=/tmp/mysql-init

Your root password is now changed. Make sure to shutdown server properly to save password change. In new terminal window execute

mysqladmin -u root -p shutdown

and enter your new pass.

Start your service and remove the init file

brew services start mysql
rm /tmp/mysql-init

Tested on mysql version 8.0.19

Change working directory in my current shell context when running Node script

What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.

When you are on the commandline and you go to execute your Node script, your current process (bash, zsh, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.

There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &) and as it ran, it started changing your working directory or overriding your PATH. That would be a nightmare.

If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile:

do_cool_thing() {
  cd "/Users"
  echo "Hey, I'm in $PWD"
}

and then this cool thing is doable:

$ pwd
/Users/spike
$ do_cool_thing
Hey, I'm in /Users
$ pwd
/Users

If you need to do more complex things in addition, you could always call out to your nodejs script from that function.

This is the only way you can accomplish what you're trying to do.

What svn command would list all the files modified on a branch?

This will do it I think:

svn diff -r 22334:HEAD --summarize <url of the branch>

How do I include the string header?

Use this:

#include < string>

What's with the dollar sign ($"string")

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Display all dataframe columns in a Jupyter Python Notebook

I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

You can do the same for the rows too:

pd.set_option('display.max_rows', <number of rows>)

This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html

MySQL does not start when upgrading OSX to Yosemite or El Capitan

I’ve got a similar problem with MySQL on a Mac (Mac Os X Could not startup MySQL Server. Reason: 255 and also “ERROR! The server quit without updating PID file”). After a long trial and error process, finally in order to restore the file permissions, I’ve just do that:

* launch the Disk Utilities.app
* choose my drive on the left panel
* click on the “Repair disk permissions” button

This did the trick for me.

Hoping this can help someone else.

Using multiprocessing.Process with a maximum number of simultaneous processes

It might be most sensible to use multiprocessing.Pool which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.

The example from the standard docs (http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers) shows that you can also manually set the number of cores:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

And it's also handy to know that there is the multiprocessing.cpu_count() method to count the number of cores on a given system, if needed in your code.

Edit: Here's some draft code that seems to work for your specific case:

import multiprocessing

def f(name):
    print 'hello', name

if __name__ == '__main__':
    pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
    for i in xrange(0, 512):
        pool.apply_async(f, args=(i,))
    pool.close()
    pool.join()

Easiest way to toggle 2 classes in jQuery

Here is a simplified version: (albeit not elegant, but easy-to-follow)

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'

}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'

});

Alternatively, a similar solution:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});

How to match letters only using java regex, matches method?

matches method performs matching of full line, i.e. it is equivalent to find() with '^abc$'. So, just use Pattern.compile("[a-zA-Z]").matcher(str).find() instead. Then fix your regex. As @user unknown mentioned your regex actually matches only one character. You probably should say [a-zA-Z]+

How do I convert a decimal to an int in C#?

Rounding a decimal to the nearest integer

decimal a ;
int b = (int)(a + 0.5m);

when a = 49.9, then b = 50

when a = 49.5, then b = 50

when a = 49.4, then b = 49 etc.

What is the difference between Cloud Computing and Grid Computing?

There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.

Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.

Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.

There are good use cases for both styles of computing.

How to run Unix shell script from Java code?

I think you have answered your own question with

Runtime.getRuntime().exec(myShellScript);

As to whether it is good practice... what are you trying to do with a shell script that you cannot do with Java?

Get user info via Google API

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture

However, location is not returned. New YouTube accounts don't have YouTube specific usernames

Django Template Variables and Javascript

new docs says use {{ mydata|json_script:"mydata" }} to prevent code injection.

a good exmple is given here:

{{ mydata|json_script:"mydata" }}
<script>
    const mydata = JSON.parse(document.getElementById('mydata').textContent);
</script>

How to host a Node.Js application in shared hosting

I installed Node.js on bluehost.com (a shared server) using:

wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node

This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.

then

./node/bin/npm install jt-js-sample

Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

I can now use the commands:

# ~/node/bin/node -v
v0.12.4

# ~/node/bin/npm -v
2.10.1

For security reasons, I have renamed my node directory to something else.

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

What I did was: Added/Updated the following code:

framework: 'jasmine',
jasmineNodeOpts: 
{
    // Jasmine default timeout
    defaultTimeoutInterval: 60000,
    expectationResultHandler(passed, assertion) 
    {
      // do something
    },
}

How to convert string representation of list to a list?

The eval is dangerous - you shouldn't execute user input.

If you have 2.6 or newer, use ast instead of eval:

>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]

Once you have that, strip the strings.

If you're on an older version of Python, you can get very close to what you want with a simple regular expression:

>>> x='[  "A",  " B", "C","D "]'
>>> re.findall(r'"\s*([^"]*?)\s*"', x)
['A', 'B', 'C', 'D']

This isn't as good as the ast solution, for example it doesn't correctly handle escaped quotes in strings. But it's simple, doesn't involve a dangerous eval, and might be good enough for your purpose if you're on an older Python without ast.

Working Soap client example

Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Getting Database connection in pure JPA setup

I ran into this problem today and this was the trick I did, which worked for me:

   EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
   EntityManagerem = emf.createEntityManager();

   org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
   java.sql.Connection connectionObj = session.connection();

Though not the best way but does the job.

Windows Scheduled task succeeds but returns result 0x1

Windows Task scheduler (Windows server 2008r2)

Same error for me (last run result: 0x1)

Tabs

  1. Action: remove quotes/double-quotes in

program/script

and

start in

even if there is spaces in the path name...

  1. General:

Run with highest privileges

and

configure for your OS...

Now it work!

last run result: The operation completed successfully

How to see which flags -march=native will activate?

You can use the -Q --help=target options:

gcc -march=native -Q --help=target ...

The -v option may also be of use.

You can see the documentation on the --help option here.

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

Load an image from a url into a PictureBox

Here's the solution I use. I can't remember why I couldn't just use the PictureBox.Load methods. I'm pretty sure it's because I wanted to properly scale & center the downloaded image into the PictureBox control. If I recall, all the scaling options on PictureBox either stretch the image, or will resize the PictureBox to fit the image. I wanted a properly scaled and centered image in the size I set for PictureBox.

Now, I just need to make a async version...

Here's my methods:

   #region Image Utilities

    /// <summary>
    /// Loads an image from a URL into a Bitmap object.
    /// Currently as written if there is an error during downloading of the image, no exception is thrown.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static Bitmap LoadPicture(string url)
    {
        System.Net.HttpWebRequest wreq;
        System.Net.HttpWebResponse wresp;
        Stream mystream;
        Bitmap bmp;

        bmp = null;
        mystream = null;
        wresp = null;
        try
        {
            wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            wreq.AllowWriteStreamBuffering = true;

            wresp = (System.Net.HttpWebResponse)wreq.GetResponse();

            if ((mystream = wresp.GetResponseStream()) != null)
                bmp = new Bitmap(mystream);
        }
        catch
        {
            // Do nothing... 
        }
        finally
        {
            if (mystream != null)
                mystream.Close();

            if (wresp != null)
                wresp.Close();
        }

        return (bmp);
    }

    /// <summary>
    /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box.
    /// Has an optional param to center the image in the picture box if it's smaller then canvas size.
    /// </summary>
    /// <param name="image">The Image you want to load, see LoadPicture</param>
    /// <param name="canvas">The canvas you want the picture to load into</param>
    /// <param name="centerImage"></param>
    /// <returns></returns>

    public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage ) 
    {
        if (image == null || canvas == null)
        {
            return null;
        }

        int canvasWidth = canvas.Size.Width;
        int canvasHeight = canvas.Size.Height;
        int originalWidth = image.Size.Width;
        int originalHeight = image.Size.Height;

        System.Drawing.Image thumbnail =
            new Bitmap(canvasWidth, canvasHeight); // changed parm names
        System.Drawing.Graphics graphic =
                     System.Drawing.Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        /* ------------------ new code --------------- */

        // Figure out the ratio
        double ratioX = (double)canvasWidth / (double)originalWidth;
        double ratioY = (double)canvasHeight / (double)originalHeight;
        double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller

        // now we can get the new height and width
        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        // Now calculate the X,Y position of the upper-left corner 
        // (one of these will always be zero)
        int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2);

        if (!centerImage)
        {
            posX = 0;
            posY = 0;
        }
        graphic.Clear(Color.White); // white padding
        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        /* ------------- end new code ---------------- */

        System.Drawing.Imaging.ImageCodecInfo[] info =
                         ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                         100L);

        Stream s = new System.IO.MemoryStream();
        thumbnail.Save(s, info[1],
                          encoderParameters);

        return Image.FromStream(s);
    }

    #endregion

Here's the required includes. (Some might be needed by other code, but including all to be safe)

using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing;

How I generally use it:

 ImageUtil.ResizeImage(ImageUtil.LoadPicture( "http://someurl/img.jpg", pictureBox1, true);

How to enable external request in IIS Express?

There's a blog post up on the IIS team site now explaining how to enable remote connections on IIS Express. Here is the pertinent part of that post summarized:

On Vista and Win7, run the following command from an administrative prompt:

netsh http add urlacl url=http://vaidesg:8080/ user=everyone

For XP, first install Windows XP Service Pack 2 Support Tools. Then run the following command from an administrative prompt:

httpcfg set urlacl /u http://vaidesg1:8080/ /a D:(A;;GX;;;WD)

Android SQLite: Update Statement

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

Automatic confirmation of deletion in powershell

Try using the -Force parameter on Remove-Item.

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

  @Override
protected void onCreate(Bundle savedInstanceState) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.popup_window_layout, new LinearLayout(mContext), true);
    popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setContentView(view);
}

   @Override
public void onWindowFocusChanged(boolean hasFocus) {
    if (hasFocus) {
        popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
    }
}

the correct way is popupwindow.show() at onWindowFocusChanged().

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

on a rasbery pi i had

pi@raspbmc:~$ git clone http: //github.com/andreafabrizi/Dropbox-Uploader .git Cloning into 'Dropbox-Uploader'... error: Problem with the SSL CA cert (path? access rights?) while accessing http:// github.com/andreafabrizi/Dropbox-Uploader.git/info/refs fatal: HTTP request failed

so id a

sudo apt-get install ca-certificates

then

git clone http://github.com/andreafabrizi/Dropbox-Uploader.git  

worked

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

PHPDoc type hinting for array of objects?

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**
 * @return SomeObj[]
 */
function getSomeObjects() {...}

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

Why do I get "'property cannot be assigned" when sending an SMTP email?

 //Hope you find it useful, it contain too many things

    string smtpAddress = "smtp.xyz.com";
    int portNumber = 587;
    bool enableSSL = true;
    string m_userName = "[email protected]";
    string m_UserpassWord = "56436578";

    public void SendEmail(Customer _customers)
    {
        string emailID = [email protected];
        string userName = DemoUser;

        string emailFrom = "[email protected]";
        string password = "qwerty";
        string emailTo = emailID;

        // Here you can put subject of the mail
        string subject = "Registration";
        // Body of the mail
        string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
        body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
        body += "<br />";
        body += "Dear " + userName + ",";
        body += "<br />";
        body += "<p>";
        body += "Thank you for registering </p>";            
        body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
        body += " <br />";
        body += "Thanks,";
        body += "<br />";
        body += "<b>The Team</b>";
        body += "</div>";
       // this is done using  using System.Net.Mail; & using System.Net; 
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            // Can set to false, if you are sending pure text.

            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }
        }
    }

Getting mouse position in c#

To answer your specific example:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

Don't forget to add using System.Windows.Forms;, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

If you're using docker-machine (docker on Windows or OSX).

Currently docker-machine has a bug that it loses internet connection if you switch between wifi networks or wifi and cable.

Make sure you restart your docker-machine

usually: docker-machine restart default

SQL Query for Logins

EXEC sp_helplogins

You can also pass an "@LoginNamePattern" parameter to get information about a specific login:

EXEC sp_helplogins @LoginNamePattern='fred'

javascript: using a condition in switch case

Your code does not work because it is not doing what you are expecting it to do. Switch blocks take in a value, and compare each case to the given value, looking for equality. Your comparison value is an integer, but most of your case expressions resolve to a boolean value.

So, for example, say liCount = 2. Your first case will not match, because 2 != 0. Your second case, (liCount<=5 && liCount>0) evaluates to true, but 2 != true, so this case will not match either.

For this reason, as many others have said, you should use a series of if...then...else if blocks to do this.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

The same document says

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

When the original request is Get with no custom headers, the browser should not make Options request which it does now. The problem is it generates a header X-Requested-With which forces the Options request. See https://github.com/angular/angular.js/pull/1454 on how to remove this header

Post an object as data using Jquery Ajax

You may pass an object to the data option in $.ajax. jQuery will send this as regular post data, just like a normal HTML form.

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: dataO, // same as using {numberId: 1, companyId: 531}
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert('In Ajax');
    }
});

How do I use Join-Path to combine more than two strings into a file path?

Join-Path is not exactly what you are looking for. It has multiple uses but not the one you are looking for. An example from Partying with Join-Path:

Join-Path C:\hello,d:\goodbye,e:\hola,f:\adios world
C:\hello\world
d:\goodbye\world
e:\hola\world
f:\adios\world

You see that it accepts an array of strings, and it concatenates the child string to each creating full paths. In your example, $path = join-path C: "Program Files" "Microsoft Office". You are getting the error since you are passing three positional arguments and join-path only accepts two. What you are looking for is a -join, and I could see this being a misunderstanding. Consider instead this with your example:

"C:","Program Files","Microsoft Office" -join "\"

-Join takes the array of items and concatenates them with \ into a single string.

C:\Program Files\Microsoft Office

Minor attempt at a salvage

Yes, I will agree that this answer is better, but mine could still work. Comments suggest there could be an issue with slashes, so to keep with my concatenation approach you could do this as well.

"C:","\\Program Files\","Microsoft Office\" -join "\" -replace "(?!^\\)\\{2,}","\"

So if there are issues with extra slashes it could be handled as long as they are not in the beginning of the string (allows UNC paths). [io.path]::combine('c:\', 'foo', '\bar\') would not work as expected and mine would account for that. Both require proper strings for input as you cannot account for all scenarios. Consider both approaches, but, yes, the other higher-rated answer is more terse, and I didn't even know it existed.

Also, would like to point out, my answer explains how what the OP doing was wrong on top of providing a suggestion to address the core problem.

Multi-dimensional associative arrays in JavaScript

    var myObj = [];
    myObj['Base'] = [];
    myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['Base']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };

    myObj['SC1'] = [];
    myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['SC1']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };


    console.log(myObj);

    if ('Base' in myObj) {
      console.log('Base found');

      if ('Base.panel.panel_base' in myObj['Base'])  {
        console.log('Base.panel.panel_base found'); 


      console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);  
      myObj['Base']['Base.panel.panel_base'] = 'new Value';
      console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
      }
    }

Output:

  • Base found
  • Base.panel.panel_base found
  • old value: Base
  • new value: new Value

The array operation works. There is no problem.

Iteration:

     Object.keys(myObj['Base']).forEach(function(key, index) {            
        var value = objcons['Base'][key];                   
      }, myObj);

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

You may convert latitude-longitude to UTM format which is metric format that may help you to calculate distances. Then you can easily decide if point falls into specific location.

Regexp Java for password validation

A more general answer which accepts all the special characters including _ would be slightly different:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\W|\_])(?=\S+$).{8,}$

The difference (?=.*[\W|\_]) translates to "at least one of all the special characters including the underscore".

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Properly embedding Youtube video into bootstrap 3.0 page

It also depend on how you style your site with bootstrap. In my example, I am using col-md-12 for my video div, and add class col-sm-12 for the iframe, so when resize to smaller screen, the video will not view squeezed. I add also height to the iframe:

<div class="col-md-12">
<iframe class="col-sm-12" height="333" frameborder="0" wmode="Opaque" allowfullscreen="" src="https://www.youtube.com/embed/oqDRPoPDehE?wmode=transparent">
</div>

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783