Programs & Examples On #Touchjson

How to compare strings in an "if" statement?

You're looking for the function strcmp, or strncmp from string.h.

Since strings are just arrays, you need to compare each character, so this function will do that for you:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}

Further reading: strcmp at cplusplus.com

What does an exclamation mark mean in the Swift language?

If you've come from a C-family language, you will be thinking "pointer to object of type X which might be the memory address 0 (NULL)", and if you're coming from a dynamically typed language you'll be thinking "Object which is probably of type X but might be of type undefined". Neither of these is actually correct, although in a roundabout way the first one is close.

The way you should be thinking of it is as if it's an object like:

struct Optional<T> {
   var isNil:Boolean
   var realObject:T
}

When you're testing your optional value with foo == nil it's really returning foo.isNil, and when you say foo! it's returning foo.realObject with an assertion that foo.isNil == false. It's important to note this because if foo actually is nil when you do foo!, that's a runtime error, so typically you'd want to use a conditional let instead unless you are very sure that the value will not be nil. This kind of trickery means that the language can be strongly typed without forcing you to test if values are nil everywhere.

In practice, it doesn't truly behave like that because the work is done by the compiler. At a high level there is a type Foo? which is separate to Foo, and that prevents funcs which accept type Foo from receiving a nil value, but at a low level an optional value isn't a true object because it has no properties or methods; it's likely that in fact it is a pointer which may by NULL(0) with the appropriate test when force-unwrapping.

There other situation in which you'd see an exclamation mark is on a type, as in:

func foo(bar: String!) {
    print(bar)
}

This is roughly equivalent to accepting an optional with a forced unwrap, i.e.:

func foo(bar: String?) {
    print(bar!)
}

You can use this to have a method which technically accepts an optional value but will have a runtime error if it is nil. In the current version of Swift this apparently bypasses the is-not-nil assertion so you'll have a low-level error instead. Generally not a good idea, but it can be useful when converting code from another language.

Switch: Multiple values in one case?

You have to do something like:

case 1:
case 2:
case 3:
//do stuff
break;

Export to CSV via PHP

Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);

// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
    fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();

// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
    $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
    $csv .= '"' . $row['id'] . '",';
    $csv .= '"' . $row['name'] . '",';
    $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
    $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
    $csv .= PHP_EOL;
}
return $csv;

This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

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

For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.

One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

It's actually do-able without JavaScript, but using pure CSS + HTML with sticky position. Just add "position:sticky" to the cells you'd like to freeze.

For building a table, you can either use or CSS grid, and this technique works on both of them.

Here is an example formatting with table tag ( live demo here ):

<table>
  <tr><th class="head"></th class="head"><th></th> ... </tr>
  <tr><th class="head"></th>             <th></th> ... </tr>
...
</table>
<style type="text/css">
  .head { position: sticky; top: 0; left: 0;}
</style>

And here is an example with CSS Grid ( live demo here ):

<div class="grid">
   <!-- cells to freeze -->
   <div class="entry head"></div>
   <div class="entry head"></div>
   ...
   <!-- normal cells -->
   <div class="entry"></div>
   ...
</div>
<style type="text/css">
  .grid {
    display: grid;
    grid-template-columns: repeat(<your-cell-count>, <cell-size>); 
  } 
  .entry.head { position: sticky; top: 0; left: 0 }
</style>

You probably will need to take care of the cells frozen both horizontally and vertically ( e.g., setting a z-index larger than others ) but it will be still CSS thing.

I think the main drawback of this approach is, probably, the browser compatibility issue. Check Can I Use CSS-sticky and Can I use CSS grid before using these techniques.

How to discover number of *logical* cores on Mac OS X?

You can do this using the sysctl utility:

sysctl -n hw.ncpu

Add multiple items to a list

Code check:

This is offtopic here but the people over at CodeReview are more than happy to help you.

I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

Lists:

As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

Lists are very straightforward to use but take a look at the related documentation anyway.

A very simple example to keep multiple bikes in a list:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

And to iterate over the list you can use the foreach statement:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

How to assign an exec result to a sql variable?

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO

So yes, it should work that way.

Table border left and bottom

you can use these styles:

style="border-left: 1px solid #cdd0d4;"  
style="border-bottom: 1px solid #cdd0d4;"
style="border-top: 1px solid #cdd0d4;"
style="border-right: 1px solid #cdd0d4;"

with this you want u must use

<td style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;">  

or

<img style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;"> 

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

The reason for what you faced is that the PDBs ("PDB stands for Program Database, a proprietary file format (developed by Microsoft) for storing debugging information about a program) are not up-to-date, this may be due to some reasons:

1- As Bevan said, you may be debugging another application!

2- You are debugging another version of the same application. For example, you attached a previously built application with the current version of the code for debugging without (re)building it.

Cleaning or Rebuilding the Solution solves such problems for me.

To make sure the problem is not yours, try debugging the same application with VS 2008 (I am afraid it may be a bug in VS 2010 -- it is still beta!).

How to add extra whitespace in PHP?

You can also use this

str_repeat("\x20", $numberOfRepeats);

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows

List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
    FirstName = (string)x["first_name"],
    Selected = (bool)x["selected"]
}).ToList();

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

Convert list to dictionary using linq and not worrying about duplicates

In case we want all the Person (instead of only one Person) in the returning dictionary, we could:

var _people = personList
.GroupBy(p => p.FirstandLastName)
.ToDictionary(g => g.Key, g => g.Select(x=>x));

Home does not contain an export named Home

This is a case where you mixed up default exports and named exports.

When dealing with the named exports, if you try to import them you should use curly braces as below,

import { Home } from './layouts/Home'; // if the Home is a named export

In your case the Home was exported as a default one. This is the one that will get imported from the module, when you don’t specify a certain name of a certain piece of code. When you import, and omit the curly braces, it will look for the default export in the module you’re importing from. So your import should be,

import Home from './layouts/Home'; // if the Home is a default export

Some references to look :

In Javascript, how to conditionally add a member to an object?

i prefere, using code this it, you can run this code

const three = {
  three: 3
}

// you can active this code, if you use object `three is null`
//const three = {}

const number = {
  one: 1,
  two: 2,
  ...(!!three && three),
  four: 4
}

console.log(number);

Design Android EditText to show error message as described by google

There's no need to use a third-party library since Google introduced the TextInputLayout as part of the design-support-library.

Following a basic example:

Layout

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:errorEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />

</android.support.design.widget.TextInputLayout>

Note: By setting app:errorEnabled="true" as an attribute of the TextInputLayout it won't change it's size once an error is displayed - so it basically blocks the space.

Code

In order to show the Error below the EditText you simply need to call #setError on the TextInputLayout (NOT on the child EditText):

TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("You need to enter a name");

Result

picture showing the edit text with the error message

To hide the error and reset the tint simply call til.setError(null).


Note

In order to use the TextInputLayout you have to add the following to your build.gradle dependencies:

dependencies {
    compile 'com.android.support:design:25.1.0'
}

Setting a custom color

By default the line of the EditText will be red. If you need to display a different color you can use the following code as soon as you call setError.

editText.getBackground().setColorFilter(getResources().getColor(R.color.red_500_primary), PorterDuff.Mode.SRC_ATOP);

To clear it simply call the clearColorFilter function, like this:

editText.getBackground().clearColorFilter();

How to update (append to) an href in jquery?

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Convert Enum to String

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToString and GetName would be that GetName has to verify a few things first:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.

.ToString doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString method doesn't have the same verification issues as the static methods, I would conclude that .ToString is the fastest way to get the value as a string.

How to use the addr2line command in Linux?

You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.

Given the VA 0x4005BDC by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps file while your program is running. The line of interest is the text segment of your process, which is identifiable by the permissions r-xp and the name of your program or library.

Let's say that the base VA is 0x0x4005000. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc. Then, supply that to add2line:

addr2line -e a.out -j .text 0xbdc

And see if that gets you your line number.

Two values from one input in python?

Two inputs separated by space:

x,y=input().split()

Looping over arrays, printing both index and value

In bash 4, you can use associative arrays:

declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
    echo "key: $key, value: ${foo[$key]}"
done

# output
# $ key: 0, value bar.
# $ key: 35, value baz.

In bash 3, this works (also works in zsh):

map=( )
map+=("0:bar")
map+=("35:baz")

for keyvalue in "${map[@]}" ; do
    key=${keyvalue%%:*}
    value=${keyvalue#*:}
    echo "key: $key, value $value."
done

How to create a session using JavaScript?

You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/

include the jStorage.js script into your html

<script src="jStorage.js"></script>

Then in your javascript place the sessiontoken into the a key like this

$.jStorage.set("YOUR_KEY",session_id);

Where "YOUR_KEY" is the key using which you can access you session_id , like this:

var id = $.jStorage.get("YOUR_KEY");

raw_input function in Python

raw_input() was renamed to input() in Python 3.

From http://docs.python.org/dev/py3k/whatsnew/3.0.html

Why shouldn't `&apos;` be used to escape single quotes?

If you really need single quotes, apostrophes, you can use

html    | numeric | hex
&lsquo; | &#145;  | &#x91; // for the left/beginning single-quote and
&rsquo; | &#146;  | &#x92; // for the right/ending single-quote

how to pass list as parameter in function

public void SomeMethod(List<DateTime> dates)
{
    // do something
}

Initialize class fields in constructor or at declaration?

Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:

  • Fields in static classes/methods
  • Fields typed as static/final/et al

I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.

What is the use of a private static variable in Java?

private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}

OracleCommand SQL Parameters Binding

Remove single quotes around @username, and with respect to oracle use : with parameter name instead of @, like:

OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                           WHERE domain_user_name = :userName", db);
oraCommand.Parameters.Add(new OracleParameter("userName", domainUser));

Source: Using Parameters

if checkbox is checked, do this

Optimal implementation

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});

Demo

_x000D_
_x000D_
$('#checkbox').on('change', function(){_x000D_
    $('p').css('color', this.checked ? '#09f' : '');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>_x000D_
<input id="checkbox" type="checkbox" /> _x000D_
<p>_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do_x000D_
    eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
</p>_x000D_
<p>_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco_x000D_
    laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu_x000D_
    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
    proident, sunt in culpa qui officia deserunt mollit anim id est_x000D_
    laborum._x000D_
</p>
_x000D_
_x000D_
_x000D_

Are there constants in JavaScript?

Are you trying to protect the variables against modification? If so, then you can use a module pattern:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.

runOnUiThread in fragment

You can also post runnable using the view from any other thread. But be sure that the view is not null:

 tView.post(new Runnable() {
                    @Override
                    public void run() {
                        tView.setText("Success");
                    }
                });

According to the Documentation:

"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For Python 3, I did:

sudo apt install python3-dev postgresql postgresql-contrib python3-psycopg2 libpq-dev

and then I was able to do:

pip3 install psycopg2

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

Reset C int array to zero : the fastest way?

zero(myarray); is all you need in C++.

Just add this to a header:

template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
    memset(arr, 0, SIZE*sizeof(T));
}

How to create a numpy array of all True or all False?

If it doesn't have to be writeable you can create such an array with np.broadcast_to:

>>> import numpy as np
>>> np.broadcast_to(True, (2, 5))
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

If you need it writable you can also create an empty array and fill it yourself:

>>> arr = np.empty((2, 5), dtype=bool)
>>> arr.fill(1)
>>> arr
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

These approaches are only alternative suggestions. In general you should stick with np.full, np.zeros or np.ones like the other answers suggest.

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

How to set a default Value of a UIPickerView

TL:DR version:

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

OR you didn't use the the following method to get the selected item from your picker

- (NSInteger)selectedRowInComponent:(NSInteger)component

This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.

Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview


EDIT:

An example of manually setting and getting of a selected row in a UIPickerView:

the .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

the .m file:

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [source count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [source objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

EDIT for Swift solution (Source: Dan Beaulieu's answer)

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

Filter object properties by key in ES6

If you are OK with using ES6 syntax, I find that the cleanest way to do this, as noted here and here is:

const data = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const { item2, ...newData } = data;

Now, newData contains:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

Or, if you have the key stored as a string:

const key = 'item2';
const { [key]: _, ...newData } = data;

In the latter case, [key] is converted to item2 but since you are using a const assignment, you need to specify a name for the assignment. _ represents a throw away value.

More generally:

const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...

Not only does this reduce your operation to a one-liner but it also doesn't require you to know what the other keys are (those that you want to preserve).

A simple utility function would look like this:

function removePropFromObject(obj, prop) {
  const { [prop]: _, ...rest } = obj
  return { ...rest }
}

How do you cast a List of supertypes to a List of subtypes?

casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:

List<? extends TestA> myList = new ArrayList<TestA>();

You still have type checking to do when you are using the objects in the list.

How can I get the list of files in a directory using C or C++?

System call it!

system( "dir /b /s /a-d * > file_names.txt" );

Then just read the file.

EDIT: This answer should be considered a hack, but it really does work (albeit in a platform specific way) if you don't have access to more elegant solutions.

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Access to Image from origin 'null' has been blocked by CORS policy

In this case the CORS problem has been caused by using the wrong source constructor in OpenLayers. ol.source.OSM is intended for accessing the default OpenStreetMap tiles from the web and for that reason defaults to crossOrigin:'anonymous'. If you are using a local source URL you should use the generic ol.source.XYZ constructor which doesn't default the crossOrigin setting (which is why setting crossOrigin:null above happened to work). And it is perfectly legitimate want to use file protocol for maps, for example on an SD card of a mobile device.

Function to calculate distance between two coordinates

Try this. It is in VB.net and you need to convert it to Javascript. This function accepts parameters in decimal minutes.

    Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
    long1 = Double.Parse(long1)
    lat1 = Double.Parse(lat1)
    long2 = Double.Parse(long2)
    lat2 = Double.Parse(lat2)

    'conversion to radian
    lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
    long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
    lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
    long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0

    ' use to different earth axis length
    Dim a As Double = 6378137.0        ' Earth Major Axis (WGS84)
    Dim b As Double = 6356752.3142     ' Minor Axis
    Dim f As Double = (a - b) / a        ' "Flattening"
    Dim e As Double = 2.0 * f - f * f      ' "Eccentricity"

    Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
    Dim cos As Double = Math.Cos(lat1)
    Dim x As Double = beta * cos * Math.Cos(long1)
    Dim y As Double = beta * cos * Math.Sin(long1)
    Dim z As Double = beta * (1 - e) * Math.Sin(lat1)

    beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
    cos = Math.Cos(lat2)
    x -= (beta * cos * Math.Cos(long2))
    y -= (beta * cos * Math.Sin(long2))
    z -= (beta * (1 - e) * Math.Sin(lat2))

    Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function

Edit The converted function in javascript

function calculateDistance(lat1, long1, lat2, long2)
  {    

      //radians
      lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;      
      long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;    
      lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;   
      long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;       


      // use to different earth axis length    
      var a = 6378137.0;        // Earth Major Axis (WGS84)    
      var b = 6356752.3142;     // Minor Axis    
      var f = (a-b) / a;        // "Flattening"    
      var e = 2.0*f - f*f;      // "Eccentricity"      

      var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));    
      var cos = Math.cos( lat1 );    
      var x = beta * cos * Math.cos( long1 );    
      var y = beta * cos * Math.sin( long1 );    
      var z = beta * ( 1 - e ) * Math.sin( lat1 );      

      beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));    
      cos = Math.cos( lat2 );   
      x -= (beta * cos * Math.cos( long2 ));    
      y -= (beta * cos * Math.sin( long2 ));    
      z -= (beta * (1 - e) * Math.sin( lat2 ));       

      return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);  
    }

CAML query with nested ANDs and ORs for multiple fields

This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:

        private static void Main(string[] args)
        {
            var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
            var whereClause =
                new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
            var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");

            string[] values = {"1", "2", "3", "4", "5", "6"};

            query["WhereClauses"] = NestEq(whereClause, andClause, values);

            Console.WriteLine(query);
        }

And here's the code:

   private static string MakeExpression(PropertyString nestClause, string value)
        {
            var expr = nestClause.New();
            expr["NestClauseValue"] = value;
            return expr.ToString();
        }

        /// <summary>
        /// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
        /// </summary>
        /// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
        /// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
        /// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
        public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
        {
            if (pos > nestClauseValues.Length)
            {
                return "";
            }

            if (nestClauseValues.Length == 1)
            {
                return MakeExpression(whereClause, nestClauseValues[0]);
            }

            var expr = nestingExpression.New();
            if (pos == nestClauseValues.Length - 2)
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
                return expr.ToString();
            }
            else
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
                return expr.ToString();
            }
        }






          public class PropertyString
    {
        private string _propStr;

        public PropertyString New()
        {
            return new PropertyString(_propStr );
        }

        public PropertyString(string propStr)
        {
            _propStr = propStr;
            _properties = new Dictionary<string, string>();
        }

        private Dictionary<string, string> _properties;
        public string this[string key]
        {
            get
            {
                return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
            }
            set
            {
                if (_properties.ContainsKey(key))
                {
                    _properties[key] = value;
                }
                else
                {
                    _properties.Add(key, value);
                }
            }
        }



        /// <summary>
        /// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you 
        /// </summary>
        /// <param name="originalStr"></param>
        /// <param name="keyValuePairPropertiesDictionary"></param>
        /// <returns></returns>
        public override string ToString()
        {
            string modifiedStr = _propStr;
            foreach (var keyvaluePair in _properties)
            {
                modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
            }

            return modifiedStr;
        }
    }

Use of PUT vs PATCH methods in REST API real life scenarios

Let me quote and comment more closely the RFC 7231 section 4.2.2, already cited in earlier comments :

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent.

(...)

Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response. For example, if a client sends a PUT request and the underlying connection is closed before any response is received, then the client can establish a new connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.

So, what should be "the same" after a repeated request of an idempotent method? Not the server state, nor the server response, but the intended effect. In particular, the method should be idempotent "from the point of view of the client". Now, I think that this point of view shows that the last example in Dan Lowe's answer, which I don't want to plagiarize here, indeed shows that a PATCH request can be non-idempotent (in a more natural way than the example in Jason Hoetger's answer).

Indeed, let's make the example slightly more precise by making explicit one possible intend for the first client. Let's say that this client goes through the list of users with the project to check their emails and zip codes. He starts with user 1, notices that the zip is right but the email is wrong. He decides to correct this with a PATCH request, which is fully legitimate, and sends only

PATCH /users/1
{"email": "[email protected]"}

since this is the only correction. Now, the request fails because of some network issue and is re-submitted automatically a couple of hours later. In the meanwhile, another client has (erroneously) modified the zip of user 1. Then, sending the same PATCH request a second time does not achieve the intended effect of the client, since we end up with an incorrect zip. Hence the method is not idempotent in the sense of the RFC.

If instead the client uses a PUT request to correct the email, sending to the server all properties of user 1 along with the email, his intended effect will be achieved even if the request has to be re-sent later and user 1 has been modified in the meanwhile --- since the second PUT request will overwrite all changes since the first request.

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Print all but the first three columns

Another way to avoid using the print statement:

 $ awk '{$1=$2=$3=""}sub("^"FS"*","")' file

In awk when a condition is true print is the default action.

GoogleMaps API KEY for testing

Updated Answer

As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

This answer is no longer valid

As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

How to find children of nodes using BeautifulSoup

Perhaps you want to do

soup.find("li", { "class" : "test" }).find('a')

Opening a .ipynb.txt File

go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done

How do I remove a single file from the staging area (undo git add)?

If you want to remove files following a certain pattern and you are using git rm --cached, you can use file-glob patterns too.

See here.

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

CSS list item width/height does not work

Remove the <br> from the .navcontainer-top li styles.

Changing factor levels with dplyr mutate

I'm not quite sure I understand your question properly, but if you want to change the factor levels of cyl with mutate() you could do:

df <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))

You would get:

#> str(df$cyl)
# Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

Multiple commands in an alias for bash

So use a semi-colon:

alias lock='gnome-screensaver; gnome-screen-saver-command --lock'

This doesn't work well if you want to supply arguments to the first command. Alternatively, create a trivial script in your $HOME/bin directory.

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

send mail from linux terminal in one line

echo "Subject: test" | /usr/sbin/sendmail [email protected]

This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.

Checking if a list is empty with LINQ

Ok, so what about this one?

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    return !enumerable.GetEnumerator().MoveNext();
}

EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards

How do I write a compareTo method which compares objects?

I wouldn't have an Object type parameter, no point in casting it to Student if we know it will always be type Student.

As for an explanation, "result == 0" will only occur when the last names are identical, at which point we compare the first names and return that value instead.

public int Compare(Object obj)
{       
    Student student = (Student) obj;
    int result = this.getLastName().compareTo( student.getLastName() );

    if ( result == 0 )
    {
        result = this.getFirstName().compareTo( student.getFirstName() );
    }

    return result;
}

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

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.

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this happen in Visual Studio 2015 too for an interesting reason. Just adding it here in case it happens to someone else.

I already had number of files in project and I was adding another one that would have main function in it, however when I initially added the file I made a typo in the extension (.coo instead of .cpp). I corrected that but when I was done I got this error. It turned out that Visual Studio was being smart and when file was added it decided that it is not a source file due to the initial extension.

Right-clicking on file in solution explorer and selecting Properties -> General -> ItemType and setting it to "C/C++ compiler" fixed the issue.

How to download/checkout a project from Google Code in Windows?

If you install TortoiseSVN you can use SVN under windows. It also gives you the SVN binaries. You needn't do the checkout from the command-line though as it integrates into Windows Explorer for you.

Select elements by attribute

In addition to selecting all elements with an attribute $('[someAttribute]') or $('input[someAttribute]') you can also use a function for doing boolean checks on an object such as in a click handler:

if(! this.hasAttribute('myattr') ) { ...

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

How to get URL parameter using jQuery or plain JavaScript?

_x000D_
_x000D_
var RequestQuerystring;_x000D_
(window.onpopstate = function () {_x000D_
    var match,_x000D_
        pl = /\+/g,  // Regex for replacing addition symbol with a space_x000D_
        search = /([^&=]+)=?([^&]*)/g,_x000D_
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },_x000D_
        query = window.location.search.substring(1);_x000D_
_x000D_
    RequestQuerystring = {};_x000D_
    while (match = search.exec(query))_x000D_
        RequestQuerystring[decode(match[1])] = decode(match[2]);_x000D_
})();
_x000D_
_x000D_
_x000D_

RequestQuerystring is now an object with all you parameters

What is the difference between HTML tags and elements?

Tags and Elements are not the same.

Elements


They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.

Eg:

<p>This is the <span>Home</span> page</p>

Tags


Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.

The browser sees the letters '

' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '

' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.

- Opening tag.

- Closing tagenter image description here

Regular expression negative lookahead

If you revise your regular expression like this:

drupal-6.14/(?=sites(?!/all|/default)).*
             ^^

...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:

drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall

Changing ?= to ?! to match your original regex simply negates those matches:

drupal-6.14/(?!sites(?!/all|/default)).*
             ^^

So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:

drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42

But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:

drupal-6.14/foo
drupal-6.14/xsites

Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

The total number of locks exceeds the lock table size

I found another way to solve it - use Table Lock. Sure, it can be unappropriate for your application - if you need to update table at same time.

See: Try using LOCK TABLES to lock the entire table, instead of the default action of InnoDB's MVCC row-level locking. If I'm not mistaken, the "lock table" is referring to the InnoDB internal structure storing row and version identifiers for the MVCC implementation with a bit identifying the row is being modified in a statement, and with a table of 60 million rows, probably exceeds the memory allocated to it. The LOCK TABLES command should alleviate this problem by setting a table-level lock instead of row-level:

SET @@AUTOCOMMIT=0;
LOCK TABLES avgvol WRITE, volume READ;
INSERT INTO avgvol(date,vol)
SELECT date,avg(vol) FROM volume
GROUP BY date;
UNLOCK TABLES;

Jay Pipes, Community Relations Manager, North America, MySQL Inc.

X close button only using css

You can use svg.

_x000D_
_x000D_
<svg viewPort="0 0 12 12" version="1.1"_x000D_
     xmlns="http://www.w3.org/2000/svg">_x000D_
    <line x1="1" y1="11" _x000D_
          x2="11" y2="1" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
    <line x1="1" y1="1" _x000D_
          x2="11" y2="11" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Set environment variables on Mac OS X Lion

Here's a bit more information specifically regarding the PATH variable in Lion OS 10.7.x:

If you need to set the PATH globally, the PATH is built by the system in the following order:

  1. Parsing the contents of the file /private/etc/paths, one path per line
  2. Parsing the contents of the folder /private/etc/paths.d. Each file in that folder can contain multiple paths, one path per line. Load order is determined by the file name first, and then the order of the lines in the file.
  3. A setenv PATH statement in /private/etc/launchd.conf, which will append that path to the path already built in #1 and #2 (you must not use $PATH to reference the PATH variable that has been built so far). But, setting the PATH here is completely unnecessary given the other two options, although this is the place where other global environment variables can be set for all users.

These paths and variables are inherited by all users and applications, so they are truly global -- logging out and in will not reset these paths -- they're built for the system and are created before any user is given the opportunity to login, so changes to these require a system restart to take effect.

BTW, a clean install of OS 10.7.x Lion doesn't have an environment.plist that I can find, so it may work but may also be deprecated.

How to create a directory and give permission in single command

install -d -m 0777 /your/dir

should give you what you want. Be aware that every user has the right to write add and delete files in that directory.

How to concatenate characters in java?

I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:

String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";

The first is evaluated at compile-time. The second is evaluated at run-time.

So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.

If the characters are constant, this is fine:

String s = "" + 'a' + 'b' + 'c';

If however they aren't, consider this:

String concat(char... chars) {
  if (chars.length == 0) {
    return "";
  }
  StringBuilder s = new StringBuilder(chars.length);
  for (char c : chars) {
    s.append(c);
  }
  return s.toString();
}

as an appropriate solution.

However some might be tempted to optimise:

String s = "Name: '" + name + "'"; // String name;

into this:

String s = new StringBuilder().append("Name: ").append(name).append("'").toString();

While this is well-intentioned, the bottom line is DON'T.

Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.

For low-level optimisation the compiler is better at optimising code than you are.

Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.

Populating a database in a Laravel migration file

I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:

public function up() {
        Schema::create('parent_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
        ParentCategory::create(
            [
                'id' => 1,
                'name' => 'Occasions',
            ],
        );
    }

This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8

How do you check whether a number is divisible by another number (Python)?

I had the same approach. Because I didn't understand how to use the module(%) operator.

6 % 3 = 0 *This means if you divide 6 by 3 you will not have a remainder, 3 is a factor of 6.

Now you have to relate it to your given problem.

if n % 3 == 0 *This is saying, if my number(n) is divisible by 3 leaving a 0 remainder.

Add your then(print, return) statement and continue your

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

OpenCV get pixel channel value from Mat image

The below code works for me, for both accessing and changing a pixel value.

For accessing pixel's channel value :

for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            uchar col = intensity.val[k]; 
        }   
    }
}

For changing a pixel value of a channel :

uchar pixValue;
for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b &intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            // calculate pixValue
            intensity.val[k] = pixValue;
        }
     }
}

`

Source : Accessing pixel value

Connection to SQL Server Works Sometimes

In my case, the parameter Persist Security Info=true with the user and password in connection string is causing the problem. Removing the parameter or set to false solve the problem.

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

Run script with rc.local: script works, but not at boot

I got my script to work by editing /etc/rc.local then issuing the following 3 commands.

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults

Now the script works at boot.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}

Why use @PostConstruct?

If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.

However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

How do I determine if a checkbox is checked?

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<label><input class="lifecheck" id="lifecheck" type="checkbox" checked >Lives</label>_x000D_
_x000D_
<script type="application/javascript" >_x000D_
    lfckv = document.getElementsByClassName("lifecheck");_x000D_
    if (true === lfckv[0].checked) {_x000D_
      alert('the checkbox is checked');_x000D_
    }_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

so after you can add event in javascript to have dynamical event affected with the checkbox .

thanks

AWS ssh access 'Permission denied (publickey)' issue

In my case (Mac OS X), the problem was the file's break type. Try this:

1.- Open the .pem file with TextWrangler

2.- At Bottom of app, verify if the Break Type is "Windows(CRLF)".

angular js unknown provider

At the end of the JS file to close the factory function I had

});

instead of

}());

Android: How to overlay a bitmap and draw over a bitmap?

I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.

Read more or download demo here

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 10, 10, null);
        return result;
    }

and call the above function on button click and pass the two images to our function as shown below

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

For more than two images, you can follow this link, how to merge multiple images programmatically on android

sqlplus statement from command line

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF

send checkbox value in PHP form

replace:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

with:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

then replace this line of code:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"

with:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";

How to programmatically set the ForeColor of a label to its default?

Easy

if (lblExample.ForeColor != System.Drawing.Color.Red)
{
    lblExample.ForeColor = System.Drawing.Color.Red;
}
else
{
    lblExample.ForeColor = new System.Drawing.Color();
}

How can my iphone app detect its own version number?

This is what I did in my application

NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

Hopefully this simple answer will help somebody...

Reading Datetime value From Excel sheet

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:

excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
    Date: {21/02/2013 00:00:00}
    Day: 21
    DayOfWeek: Thursday
    DayOfYear: 52
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 2
    Second: 0
    Ticks: 634970016000000000
    TimeOfDay: {00:00:00}
    Year: 2013

excelApp.Range[namedRange].Value2
41326.0

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

Add a common Legend for combined ggplots

If you are plotting the same variables in both plots, the simplest way would be to combine the data frames into one, then use facet_wrap.

For your example:

big_df <- rbind(df1,df2)

big_df <- data.frame(big_df,Df = rep(c("df1","df2"),
times=c(nrow(df1),nrow(df2))))

ggplot(big_df,aes(x=x, y=y,colour=group)) 
+ geom_point(position=position_jitter(w=0.04,h=0.02),size=1.8) 
+ facet_wrap(~Df)

Plot 1

Another example using the diamonds data set. This shows that you can even make it work if you have only one variable common between your plots.

diamonds_reshaped <- data.frame(price = diamonds$price,
independent.variable = c(diamonds$carat,diamonds$cut,diamonds$color,diamonds$depth),
Clarity = rep(diamonds$clarity,times=4),
Variable.name = rep(c("Carat","Cut","Color","Depth"),each=nrow(diamonds)))

ggplot(diamonds_reshaped,aes(independent.variable,price,colour=Clarity)) + 
geom_point(size=2) + facet_wrap(~Variable.name,scales="free_x") + 
xlab("")

Plot 2

Only tricky thing with the second example is that the factor variables get coerced to numeric when you combine everything into one data frame. So ideally, you will do this mainly when all your variables of interest are the same type.

How do I download a file with Angular2 or greater

The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                 error => console.log('Error downloading the file.'),
                 () => console.info('OK');

When the request is ready it will call the function "downloadFile" that is defined as follows:

downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;

  import 'rxjs/Rx' ;

I hope this can help you.

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

PowerShell script to return versions of .NET Framework on a machine?

This is a derivite of previous post, but this gets the latest version of the .net framework 4 in my tests.

get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL"

Which will allow you to invoke-command to remote machine:

invoke-command -computername server01 -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release} 

Which sets up this possibility with ADModule and naming convention prefix:

get-adcomputer -Filter 'name -like "*prefix*"' | % {invoke-command -computername $_.name -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release} | ft

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

Sending websocket ping/pong frame from browser

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.

javascript cell number validation

<script type="text/javascript">
    function MobileNoValidation()
    {
       var phno=/^\d{10}$/
       if(textMobileNo.value=="")
       {
        alert("Mobile No Should Not Be Empty");
       }
       else if(!textMobileNo.value.match(phno))
       {
        alert("Mobile no must be ten digit");
       }
       else
       {
        alert("valid Mobile No");
       }
    }
</script>

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Mongoose.js: Find user by username LIKE value

For dynamic search, you can follow like this also,

const { keyword, skip, limit, sort } = pagination(params);
const search = keyword
      ? {
          title: {
            $regex: new RegExp(keyword, 'i')
          }
        }
      : {};

Model.find(search)
      .sort(sort)
      .skip(skip)
      .limit(limit);

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.

Retrieve data from a ReadableStream object?

In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available here).

As an example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    // The response is a Response instance.
    // You parse the data into a useable format using `.json()`
    return response.json();
  }).then(function(data) {
    // `data` is the parsed version of the JSON returned from the above endpoint.
    console.log(data);  // { "userId": 1, "id": 1, "title": "...", "body": "..." }
  });

EDIT: If your data return type is not JSON or you don't want JSON then use text()

As an example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    return response.text();
  }).then(function(data) {
    console.log(data); // this will be a string
  });

Hope this helps clear things up.

How to Load Ajax in Wordpress

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

2.) In my ajax code i can then use my url like this

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

How do I find the current executable filename?

In addition to the answers above.

I wrote following test.exe as console application

static void Main(string[] args) {
  Console.WriteLine(
    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
  Console.WriteLine(
    System.Reflection.Assembly.GetEntryAssembly().Location);
  Console.WriteLine(
    System.Reflection.Assembly.GetExecutingAssembly().Location);
  Console.WriteLine(
    System.Reflection.Assembly.GetCallingAssembly().Location);
}

Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.

But, if I start it in the Visual Studio, the result is:

d:\test2.vhost.exe

d:\test2.exe

d:\test2.exe

C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll

The ReSharper plug-in to the Visual Studio has underlined the

System.Diagnostics.Process.GetCurrentProcess().MainModule

as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.

The GetEntryAssembly method is also not 100% "safe". MSDN:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

For my solutions, I prefer the Assembly.GetEntryAssembly().Location.

More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.

The only solution I found is

var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory, 
  System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

Using HTTPS with REST in Java

The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.

So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:

     public static String doPostSecureWithHeader(String url, String body, Map headers)
            throws Exception {
        log.info("start doPostSecureWithHeader " + url + " with param " + body);
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        Client client;
        client = Client.create();
        WebResource webResource;
        webResource = null;
        String output = null;
        try{
            SSLContext sslContext = null;
            SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
            sslContext = SSLContext.getInstance("SSL");
            sslContext
            .init(null,
                    new javax.net.ssl.TrustManager[] { secureRestClientTrustManager },
                    null);
            DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
            defaultClientConfig
            .getProperties()
            .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new com.sun.jersey.client.urlconnection.HTTPSProperties(
                            getHostnameVerifier(), sslContext));

            client = Client.create(defaultClientConfig);
            webResource = client.resource(url);

            if(headers!=null && headers.size()>0){
                for (Map.Entry entry : headers.entrySet()){
                    webResource.setProperty(entry.getKey(), entry.getValue());
                }
            }
            WebResource.Builder builder = 
                    webResource.accept("application/json");
            if(headers!=null && headers.size()>0){
                for (Map.Entry entry : headers.entrySet()){
                    builder.header(entry.getKey(), entry.getValue());
                }
            }

            ClientResponse response = builder
                    .post(ClientResponse.class, body);
            output = response.getEntity(String.class);
        }
        catch(Exception e){
            log.error(e.getMessage(),e);
            if(e.toString().contains("One or more of query value parameters are null")){
                output="-1";
            }
            if(e.toString().contains("401 Unauthorized")){
                throw e;
            }
        }
        finally {
            if (client!= null) {
                client.destroy();
            }
        }
        endTime = System.currentTimeMillis();
        log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output);
        return output;
    }

Create a new txt file using VB.NET

You could just use this

FileOpen(1, "C:\my files\2010\SomeFileName.txt", OpenMode.Output)
FileClose(1)

This opens the file replaces whatever is in it and closes the file.

How to check if a date is in a given range?

Convert both dates to timestamps then do

pseudocode:

if date_from_user > start_date && date_from_user < end_date
    return true

Java HTTPS client certificate authentication

For those of you who simply want to set up a two-way authentication (server and client certificates), a combination of these two links will get you there :

Two-way auth setup:

https://linuxconfig.org/apache-web-server-ssl-authentication

You don't need to use the openssl config file that they mention; just use

  • $ openssl genrsa -des3 -out ca.key 4096

  • $ openssl req -new -x509 -days 365 -key ca.key -out ca.crt

to generate your own CA certificate, and then generate and sign the server and client keys via:

  • $ openssl genrsa -des3 -out server.key 4096

  • $ openssl req -new -key server.key -out server.csr

  • $ openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 100 -out server.crt

and

  • $ openssl genrsa -des3 -out client.key 4096

  • $ openssl req -new -key client.key -out client.csr

  • $ openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 101 -out client.crt

For the rest follow the steps in the link. Managing the certificates for Chrome works the same as in the example for firefox that is mentioned.

Next, setup the server via:

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

Note that you have already created the server .crt and .key so you don't have to do that step anymore.

jQuery: click function exclude children.

Here is an example. Green square is parent and yellow square is child element.

Hope that this helps.

_x000D_
_x000D_
var childElementClicked;_x000D_
_x000D_
$("#parentElement").click(function(){_x000D_
_x000D_
  $("#childElement").click(function(){_x000D_
     childElementClicked = true;_x000D_
  });_x000D_
_x000D_
  if( childElementClicked != true ) {_x000D_
_x000D_
   // It is clicked on parent but not on child._x000D_
      // Now do some action that you want._x000D_
      alert('Clicked on parent');_x000D_
   _x000D_
  }else{_x000D_
      alert('Clicked on child');_x000D_
    }_x000D_
    _x000D_
    childElementClicked = false;_x000D_
 _x000D_
});
_x000D_
#parentElement{_x000D_
width:200px;_x000D_
height:200px;_x000D_
background-color:green;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#childElement{_x000D_
margin-top:50px;_x000D_
margin-left:50px;_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-color:yellow;_x000D_
position:absolute;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="parentElement">_x000D_
  <div id="childElement">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

git visual diff between branches

Use git diff with a range.

git diff branch1..branch2

This will compare the tips of each branch.

If you really want some GUI software, you can try something like SourceTree which supports Mac OS X and Windows.

How to keep console window open

You forgot calling your method:

static void Main(string[] args)
{          
    StringAddString s = new StringAddString();  
    s.AddString();
}

it should stop your console, but the result might not be what you expected, you should change your code a little bit:

Console.WriteLine(string.Join(",", strings2));

Find value in an array

If you want find one value from array, use Array#find:

arr = [1,2,6,4,9] 
arr.find {|e| e % 3 == 0}   #=>  6

See also:

arr.select {|e| e % 3 == 0} #=> [ 6, 9 ]
e.include? 6              #=> true

To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in? works for any object that responds to #include?:

arr = [1, 6]
6.in? arr                 #=> true

Microsoft Web API: How do you do a Server.MapPath?

As an aside to those that stumble along across this, one nice way to run test level on using the HostingEnvironment call, is if accessing say a UNC share: \example\ that is mapped to ~/example/ you could execute this to get around IIS-Express issues:

#if DEBUG
    var fs = new FileStream(@"\\example\file",FileMode.Open, FileAccess.Read);
#else
    var fs = new FileStream(HostingEnvironment.MapPath("~/example/file"), FileMode.Open, FileAccess.Read);
#endif

I find that helpful in case you have rights to locally test on a file, but need the env mapping once in production.

Using <style> tags in the <body> with other HTML

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

Send FormData and String Data Together Through JQuery AJAX?

I try to contribute my code collaboration with my friend . modification from this forum.

$('#upload').on('click', function() {
            var fd = new FormData();
              var c=0;
              var file_data,arr;
              $('input[type="file"]').each(function(){
                  file_data = $('input[type="file"]')[c].files; // get multiple files from input file
                  console.log(file_data);
               for(var i = 0;i<file_data.length;i++){
                   fd.append('arr[]', file_data[i]); // we can put more than 1 image file
               }
              c++;
           }); 

               $.ajax({
                   url: 'test.php',
                   data: fd,
                   contentType: false,
                   processData: false,
                   type: 'POST',
                   success: function(data){
                       console.log(data);
                   }
               });
           });

this my html file

<form name="form" id="form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]"multiple>
<input type="button" name="submit" value="upload" id="upload">

this php code file

<?php 
$count = count($_FILES['arr']['name']); // arr from fd.append('arr[]')
var_dump($count);
echo $count;
var_dump($_FILES['arr']);

if ( $count == 0 ) {
   echo 'Error: ' . $_FILES['arr']['error'][0] . '<br>';
}
else {
    $i = 0;
    for ($i = 0; $i < $count; $i++) { 
        move_uploaded_file($_FILES['arr']['tmp_name'][$i], 'uploads/' . $_FILES['arr']['name'][$i]);
    }

}
?>

I hope people with same problem , can fast solve this problem. i got headache because multiple upload image.

How to destroy Fragment?

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()

How do I write a bash script to restart a process if it dies?

I use this for my npm Process

#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done

jQuery: Best practice to populate drop down?

Or maybe:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});

Group array items using object

This gives you unique colors, if you do not want duplicate values for color

_x000D_
_x000D_
var arr = [_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "green"},_x000D_
  {group: "one", color: "black"}_x000D_
]_x000D_
_x000D_
var arra = [...new Set(arr.map(x => x.group))]_x000D_
_x000D_
let reformattedArray = arra.map(obj => {_x000D_
   let rObj = {}_x000D_
   rObj['color'] = [...new Set(arr.map(x => x.group == obj ? x.color:false ))]_x000D_
       .filter(x => x != false)_x000D_
   rObj['group'] = obj_x000D_
   return rObj_x000D_
})_x000D_
console.log(reformattedArray)
_x000D_
_x000D_
_x000D_

Apply function to all elements of collection through LINQ

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

How do I remove leading whitespace in Python?

To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.

plot.new has not been called yet

Some action, very possibly not represented in the visible code, has closed the interactive screen device. It could be done either by a "click" on a close-button. (Could also be done by an extra dev.off() when plotting to a file-graphics device. This may happen if you paste in a mult-line plotting command that has a dev,off() at the end of it but errors out at the opening of the external device but then has hte dev.off() on a separate line so it accidentally closes the interactive device).

Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it. On Windows that might be window(); on a Mac, quartz(); and on a linux box, x11(). You also may need to issue a plot.new() command. I just follow orders. When I get that error I issue plot.new() and if I don't see a plot window, I issue quartz() as well. I then start over from the beginning with a new plot(., ., ...) command and any further additions to that plot screen image.

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

Passing arguments to C# generic new() of templated type

I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:

var x = Activator.CreateInstance(typeof(T), args) as T;

Why is the use of alloca() not considered good practice?

One pitfall with alloca is that longjmp rewinds it.

That is to say, if you save a context with setjmp, then alloca some memory, then longjmp to the context, you may lose the alloca memory. The stack pointer is back where it was and so the memory is no longer reserved; if you call a function or do another alloca, you will clobber the original alloca.

To clarify, what I'm specifically referring to here is a situation whereby longjmp does not return out of the function where the alloca took place! Rather, a function saves context with setjmp; then allocates memory with alloca and finally a longjmp takes place to that context. That function's alloca memory is not all freed; just all the memory that it allocated since the setjmp. Of course, I'm speaking about an observed behavior; no such requirement is documented of any alloca that I know.

The focus in the documentation is usually on the concept that alloca memory is associated with a function activation, not with any block; that multiple invocations of alloca just grab more stack memory which is all released when the function terminates. Not so; the memory is actually associated with the procedure context. When the context is restored with longjmp, so is the prior alloca state. It's a consequence of the stack pointer register itself being used for allocation, and also (necessarily) saved and restored in the jmp_buf.

Incidentally, this, if it works that way, provides a plausible mechanism for deliberately freeing memory that was allocated with alloca.

I have run into this as the root cause of a bug.

jQuery UI " $("#datepicker").datepicker is not a function"

I just ran into a similar issue. When I changed my script reference from self-closing tags (ie, <script src=".." />) to empty nodes (ie, <script src=".."></script>) my errors went away and I could suddenly reference the jQuery UI functions.

At the time, I didn't realize this was just a brain-fart of me not closing it properly to begin with. (I'm posting this simply on the chance that anyone else coming across the thread is having a similar issue.)

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden, so when setting my pictures to width: 100% the pictures would look vertically cut, and so I forced them to be visible with !important and to avoid showing the slide animation out of the box I set overflow: hidden to the container div of the slide. Hope it works for you.

UPDATE - New Solution:

Original problem -> http://jsfiddle.net/xMddf/1/ (Even if I use overflow-y: visible it becomes "auto" and actually "scroll".)

#content {
    height: 100px;
    width: 200px;
    overflow-x: hidden;
    overflow-y: visible;
}

The new solution -> http://jsfiddle.net/xMddf/2/ (I found a workaround using a wrapper div to apply overflow-x and overflow-y to different DOM elements as James Khoury advised on the problem of combining visible and hidden to a single DOM element.)

#wrapper {
    height: 100px;
    overflow-y: visible;
}
#content {
    width: 200px;
    overflow-x: hidden;
}

Fastest way to convert a dict's keys & values from `unicode` to `str`?

Just use print(*(dict.keys()))

The * can be used for unpacking containers e.g. lists. For more info on * check this SO answer.

Get generic type of class at runtime

I used follow approach:

public class A<T> {

    protected Class<T> clazz;

    public A() {
        this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Class<T> getClazz() {
        return clazz;
    }
}

public class B extends A<C> {
   /* ... */
    public void anything() {
       // here I may use getClazz();
    }
}

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

Auto refresh page every 30 seconds

Just a simple line of code in the head section can refresh the page

<meta http-equiv="refresh" content="30">

although its not a javascript function, its the simplest way to accomplish the above task hopefully.

How do I implement a progress bar in C#?

The idea behind reporting progress with the background worker is through sending a 'percent completed' event. You are yourself responsible for determining somehow 'how much' work has been completed. Unfortunately this is often the most difficult part.

In your case, the bulk of the work is database-related. There is to my knowledge no way to get progress information from the DB directly. What you can try to do however, is split up the work dynamically. E.g., if you need to read a lot of data, a naive way to implement this could be.

  • Determine how many rows are to be retrieved (SELECT COUNT(*) FROM ...)
  • Divide the actual reading in smaller chunks, reporting progress every time one chunk is completed:

    for (int i = 0; i < count; i++)
    {
        bgWorker.ReportProgress((100 * i) / count);
        // ... (read data for step i)
    }
    

Display date/time in user's locale format and time offset

You could use the following, which reports the timezone offset from GMT in minutes:

new Date().getTimezoneOffset();

Note : - this function return a negative number.

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

From official documentation :

To enable Google to crawl your app content and allow users to enter your app from search results, you must add intent filters for the relevant activities in your app manifest. These intent filters allow deep linking to the content in any of your activities. For example, the user might click on a deep link to view a page within a shopping app that describes a product offering that the user is searching for.

Using this link Enabling Deep Links for App Content you'll see how to use it.

And using this Test Your App Indexing Implementation how to test it.

The following XML snippet shows how you might specify an intent filter in your manifest for deep linking.

<activity
    android:name="com.example.android.GizmosActivity"
    android:label="@string/title_gizmos" >
    <intent-filter android:label="@string/filter_title_viewgizmos">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Accepts URIs that begin with "http://www.example.com/gizmos” -->
        <data android:scheme="http"
              android:host="www.example.com"
              android:pathPrefix="/gizmos" />
        <!-- note that the leading "/" is required for pathPrefix-->
        <!-- Accepts URIs that begin with "example://gizmos” -->
        <data android:scheme="example"
              android:host="gizmos" />

    </intent-filter>
</activity>

To test via Android Debug Bridge

$ adb shell am start
        -W -a android.intent.action.VIEW
        -d <URI> <PACKAGE>

$ adb shell am start
        -W -a android.intent.action.VIEW
        -d "example://gizmos" com.example.android

How to evaluate a math expression given in string form?

Yet another option: https://github.com/stefanhaustein/expressionparser

I have implemented this to have a simple but flexible option to permit both:

The TreeBuilder linked above is part of a CAS demo package that does symbolic derivation. There is also a BASIC interpreter example and I have started to build a TypeScript interpreter using it.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

SQL where datetime column equals today's date?

To get all the records where record created date is today's date Use the code after WHERE clause

WHERE  CAST(Submission_date AS DATE) = CAST( curdate() AS DATE)

Casting an int to a string in Python

You can use str() to cast it, or formatters:

"ME%d.txt" % (num,)

IOException: The process cannot access the file 'file path' because it is being used by another process

I got this error because I was doing File.Move to a file path without a file name, need to specify the full path in the destination.

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

MySQL DISTINCT on a GROUP_CONCAT()

GROUP_CONCAT has DISTINCT attribute:

SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ') FROM table

Failed to find 'ANDROID_HOME' environment variable

I had this issue before.
You need to add sdks\tools and sdks\build-tools to your environment path.

What does it mean to "program to an interface"?

You should look into Inversion of Control:

In such a scenario, you wouldn't write this:

IInterface classRef = new ObjectWhatever();

You would write something like this:

IInterface classRef = container.Resolve<IInterface>();

This would go into a rule-based setup in the container object, and construct the actual object for you, which could be ObjectWhatever. The important thing is that you could replace this rule with something that used another type of object altogether, and your code would still work.

If we leave IoC off the table, you can write code that knows that it can talk to an object that does something specific, but not which type of object or how it does it.

This would come in handy when passing parameters.

As for your parenthesized question "Also, how could you write a method that takes in an object that implements an Interface? Is that possible?", in C# you would simply use the interface type for the parameter type, like this:

public void DoSomethingToAnObject(IInterface whatever) { ... }

This plugs right into the "talk to an object that does something specific." The method defined above knows what to expect from the object, that it implements everything in IInterface, but it doesn't care which type of object it is, only that it adheres to the contract, which is what an interface is.

For instance, you're probably familiar with calculators and have probably used quite a few in your days, but most of the time they're all different. You, on the other hand, knows how a standard calculator should work, so you're able to use them all, even if you can't use the specific features that each calculator has that none of the other has.

This is the beauty of interfaces. You can write a piece of code, that knows that it will get objects passed to it that it can expect certain behavior from. It doesn't care one hoot what kind of object it is, only that it supports the behavior needed.

Let me give you a concrete example.

We have a custom-built translation system for windows forms. This system loops through controls on a form and translate text in each. The system knows how to handle basic controls, like the-type-of-control-that-has-a-Text-property, and similar basic stuff, but for anything basic, it falls short.

Now, since controls inherit from pre-defined classes that we have no control over, we could do one of three things:

  1. Build support for our translation system to detect specifically which type of control it is working with, and translate the correct bits (maintenance nightmare)
  2. Build support into base classes (impossible, since all the controls inherit from different pre-defined classes)
  3. Add interface support

So we did nr. 3. All our controls implement ILocalizable, which is an interface that gives us one method, the ability to translate "itself" into a container of translation text/rules. As such, the form doesn't need to know which kind of control it has found, only that it implements the specific interface, and knows that there is a method where it can call to localize the control.

make bootstrap twitter dialog modal draggable

In my case I am enabling draggable. It works.

var bootstrapDialog = new BootstrapDialog({
    title: 'Message',
    draggable: true,
    closable: false,
    size: BootstrapDialog.SIZE_WIDE,
    message: 'Hello World',
    buttons: [{
         label: 'close',
         action: function (dialogRef) {
             dialogRef.close();
         }
     }],
});
bootstrapDialog.open();

Might be it helps you.

No Spring WebApplicationInitializer types detected on classpath

xml was not in the WEB-INF folder, thats why i was getting this error, make sure that web.xml and xxx-servlet.xml is inside WEB_INF folder and not in the webapp folder .

Change a web.config programmatically with C# (.NET)

Here it is some code:

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

See more examples in this article, you may need to take a look to impersonation.

Display a jpg image on a JPanel

I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

Here's Sun's docs on the subject matter.

std::vector versus std::array in C++

If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.

Given the following declarations:

int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc;      // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc;    // initialized to [3][5]

A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.

A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.

This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.

This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.

Determining if an Object is of primitive type

The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example

System.out.println(Integer.class.isPrimitive());

prints "false", but

public static void main (String args[]) throws Exception
{
    Method m = Junk.class.getMethod( "a",null);
    System.out.println( m.getReturnType().isPrimitive());
}

public static int a()
{
    return 1;
}

prints "true"

Does Java have something like C#'s ref and out keywords?

Three solutions not officially, explicitly mentioned:

ArrayList<String> doThings() {
  //
}

void doThings(ArrayList<String> list) {
  //
}

Pair<String, String> doThings() {
  //
}

For Pair, I would recommend: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

Stop setInterval call in JavaScript

@cnu,

You can stop interval, when try run code before look ur console browser (F12) ... try comment clearInterval(trigger) is look again a console, not beautifier? :P

Check example a source:

_x000D_
_x000D_
var trigger = setInterval(function() { _x000D_
  if (document.getElementById('sandroalvares') != null) {_x000D_
    document.write('<div id="sandroalvares" style="background: yellow; width:200px;">SandroAlvares</div>');_x000D_
    clearInterval(trigger);_x000D_
    console.log('Success');_x000D_
  } else {_x000D_
    console.log('Trigger!!');_x000D_
  }_x000D_
}, 1000);
_x000D_
<div id="sandroalvares" style="background: gold; width:200px;">Author</div>
_x000D_
_x000D_
_x000D_

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

Want to show/hide div based on dropdown box selection

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("select").change(function(){_x000D_
        $(this).find("option:selected").each(function(){_x000D_
            var optionValue = $(this).attr("value");_x000D_
            if(optionValue){_x000D_
                $(".box").not("." + optionValue).hide();_x000D_
                $("." + optionValue).show();_x000D_
            } else{_x000D_
                $(".box").hide();_x000D_
            }_x000D_
        });_x000D_
    }).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
    .box{_x000D_
        color: #fff;_x000D_
        padding: 50px;_x000D_
        display: none;_x000D_
        margin-top: 10px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div>_x000D_
        <select>_x000D_
            <option>Choose Color</option>_x000D_
            <option value="red">Red</option>_x000D_
            <option value="green">Green</option>_x000D_
            <option value="blue">Blue</option>_x000D_
        </select>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Netbeans - Error: Could not find or load main class

If none of the above works (Setting Main class, Clean and Build, deleting the cache) and you have a Maven project, try:

mvn clean install

on the command line.

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

There is also a slight difference in the html output for a string data type.

Html.EditorFor:  
<input id="Contact_FirstName" class="text-box single-line" type="text" value="Greg" name="Contact.FirstName">

Html.TextBoxFor:
<input id="Contact_FirstName" type="text" value="Greg" name="Contact.FirstName">

Closing database connections in Java

Yes, you need to close Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

I think the description of the error is misleading and has originally to do with wrong usage of the player object.

I had the same issue when switching to new Videos in a Slider.

When simply using the player.destroy() function described here the problem is gone.

maxlength ignored for input type="number" in Chrome

For React users,

Just replace 10 with your max length requirement

 <input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>

Android: Share plain text using intent (to all messaging apps)

Use the code as:

    /*Create an ACTION_SEND Intent*/
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    /*This will be the actual content you wish you share.*/
    String shareBody = "Here is the share content body";
    /*The type of the content is text, obviously.*/
    intent.setType("text/plain");
    /*Applying information Subject and Body.*/
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
    intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    /*Fire!*/
    startActivity(Intent.createChooser(intent, getString(R.string.share_using)));

jQuery UI Slider (setting programmatically)

In my case with jquery slider with 2 handles only following way worked.

$('#Slider').slider('option',{values: [0.15, 0.6]});

How can I get the DateTime for the start of the week?

Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week.

    DateTime WeekBeginning(DateTime input)
    {
        do
        {
            if (input.DayOfWeek.ToString() == "Monday")
                return input;
            else
                return WeekBeginning(input.AddDays(-1));
        } while (input.DayOfWeek.ToString() == "Monday");
    }

Is <img> element block level or inline level?

Whenever you insert an image it just takes the width that the image has originally. You can add any other html element next to it and you will see that it will allow it. That makes image an "inline" element.

Add placeholder text inside UITextView in Swift?

Here is my way of solving this problem (Swift 4):

The idea was to make the simplest possible solution which allows to use placeholders of different colors, resizes to placeholders size, will not overwrite a delegate meanwhile keeping all UITextView functions work as expected.

import UIKit

class PlaceholderTextView: UITextView {
    var placeholderColor: UIColor = .lightGray
    var defaultTextColor: UIColor = .black

    private var isShowingPlaceholder = false {
        didSet {
            if isShowingPlaceholder {
                text = placeholder
                textColor = placeholderColor
            } else {
                textColor = defaultTextColor
            }
        }
    }

    var placeholder: String? {
        didSet {
            isShowingPlaceholder = !hasText
        }
    }

    @objc private func textViewDidBeginEditing(notification: Notification) {
        textColor = defaultTextColor
        if isShowingPlaceholder { text = nil }
    }

    @objc private func textViewDidEndEditing(notification: Notification) {
        isShowingPlaceholder = !hasText
    }

    // MARK: - Construction -
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        NotificationCenter.default.addObserver(self, selector: #selector(textViewDidBeginEditing(notification:)), name: UITextView.textDidBeginEditingNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(textViewDidEndEditing(notification:)), name: UITextView.textDidEndEditingNotification, object: nil)
    }

    // MARK: - Destruction -
    deinit { NotificationCenter.default.removeObserver(self) }
}

Search for "does-not-contain" on a DataFrame in pandas

You can use Apply and Lambda to select rows where a column contains any thing in a list. For your scenario :

df[df["col"].apply(lambda x:x not in [word1,word2,word3])]

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

"unable to locate adb" using Android Studio

open Studio settings-->System settings --> Android SDK --> select SDK tool tab -->> select "Android SDK platform tool" and install

How to add button tint programmatically

I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value. I succeeded by using the code:

ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);

Where color is an int value representing the colour required. This represents the simple xml ColorStateList:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:color="color here"/>
</selector>

Hope this helps.

Git Bash doesn't see my PATH

Maybe bash doesn't see your Windows path. Type env|grep PATH in bash to confirm what path it sees.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

SQL Left Join first match only

Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.

SELECT DISTINCT P2.*
FROM (
  SELECT
      IDNo
    , FirstName
    , LastName
  FROM people P
) P2

Here is some play data as requested: http://sqlfiddle.com/#!3/050e0d/3

CREATE TABLE people
(
       [entry] int
     , [IDNo] varchar(3)
     , [FirstName] varchar(5)
     , [LastName] varchar(7)
);

INSERT INTO people
    (entry,[IDNo], [FirstName], [LastName])
VALUES
    (1,'uqx', 'bob', 'smith'),
    (2,'abc', 'john', 'willis'),
    (3,'ABC', 'john', 'willis'),
    (4,'aBc', 'john', 'willis'),
    (5,'WTF', 'jeff', 'bridges'),
    (6,'Sss', 'bill', 'doe'),
    (7,'sSs', 'bill', 'doe'),
    (8,'ssS', 'bill', 'doe'),
    (9,'ere', 'sally', 'abby'),
    (10,'wtf', 'jeff', 'bridges')
;

Get a list of resources from classpath directory

This should work (if spring is not an option):

public static List<String> getFilenamesForDirnameFromCP(String directoryName) throws URISyntaxException, UnsupportedEncodingException, IOException {
    List<String> filenames = new ArrayList<>();

    URL url = Thread.currentThread().getContextClassLoader().getResource(directoryName);
    if (url != null) {
        if (url.getProtocol().equals("file")) {
            File file = Paths.get(url.toURI()).toFile();
            if (file != null) {
                File[] files = file.listFiles();
                if (files != null) {
                    for (File filename : files) {
                        filenames.add(filename.toString());
                    }
                }
            }
        } else if (url.getProtocol().equals("jar")) {
            String dirname = directoryName + "/";
            String path = url.getPath();
            String jarPath = path.substring(5, path.indexOf("!"));
            try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, StandardCharsets.UTF_8.name()))) {
                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (name.startsWith(dirname) && !dirname.equals(name)) {
                        URL resource = Thread.currentThread().getContextClassLoader().getResource(name);
                        filenames.add(resource.toString());
                    }
                }
            }
        }
    }
    return filenames;
}

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Here is where you went wrong:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

it should be:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

or

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

You have made two mistakes:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

    .subscribe(success, failure, complete);

for example:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.