Programs & Examples On #Oncreate

onCreate refers to one of the lifecycle methods for several components on the Android platform.

Android activity life cycle - what are all these methods for?

I run some logs as per answers above and here is the output:

Starting Activity

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Stopping The Activity

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

In my personal opinion only two are required onStart and onStop.

onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Start an Activity with a parameter

Put an int which is your id into the new Intent.

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();

Then grab the id in your new Activity:

Bundle b = getIntent().getExtras();
int value = -1; // or other values
if(b != null)
    value = b.getInt("key");

What's onCreate(Bundle savedInstanceState)

If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState), it can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.

... you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

source

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

UPDATE:

onActivityCreated() is deprecated from API Level 28.


onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


To sum up...
... they are all called in the Fragment but are called at different times.
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


If you want to view the official Android documentation, it can be found here:

There are also some slightly different, but less developed questions/answers here on Stack Overflow:

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

Append key/value pair to hash with << in Ruby

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash

{:key=>"value"}

hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

dynamic_cast and static_cast in C++

First, to describe dynamic cast in C terms, we have to represent classes in C. Classes with virtual functions use a "VTABLE" of pointers to the virtual functions. Comments are C++. Feel free to reformat and fix compile errors...

// class A { public: int data; virtual int GetData(){return data;} };
typedef struct A { void**vtable; int data;} A;
int AGetData(A*this){ return this->data; }
void * Avtable[] = { (void*)AGetData };
A * newA() { A*res = malloc(sizeof(A)); res->vtable = Avtable; return res; }

// class B : public class A { public: int moredata; virtual int GetData(){return data+1;} }
typedef struct B { void**vtable; int data; int moredata; } B;
int BGetData(B*this){ return this->data + 1; }
void * Bvtable[] = { (void*)BGetData };
B * newB() { B*res = malloc(sizeof(B)); res->vtable = Bvtable; return res; }

// int temp = ptr->GetData();
int temp = ((int(*)())ptr->vtable[0])();

Then a dynamic cast is something like:

// A * ptr = new B();
A * ptr = (A*) newB();
// B * aB = dynamic_cast<B>(ptr);
B * aB = ( ptr->vtable == Bvtable ? (B*) aB : (B*) 0 );

Why doesn't JavaScript have a last method?

It's easy to define one yourself. That's the power of JavaScript.

if(!Array.prototype.last) {
    Array.prototype.last = function() {
        return this[this.length - 1];
    }
}

var arr = [1, 2, 5];
arr.last(); // 5

However, this may cause problems with 3rd-party code which (incorrectly) uses for..in loops to iterate over arrays.

However, if you are not bound with browser support problems, then using the new ES5 syntax to define properties can solve that issue, by making the function non-enumerable, like so:

Object.defineProperty(Array.prototype, 'last', {
    enumerable: false,
    configurable: true,
    get: function() {
        return this[this.length - 1];
    },
    set: undefined
});

var arr = [1, 2, 5];
arr.last; // 5

Forward X11 failed: Network error: Connection refused

fill in the "X display location" did not work for me. but install MobaXterm did the job.

Print in one line dynamically

Or even simpler:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r" will overwrite from the beginning [0:] of the first print.

JSON forEach get Key and Value

Use index notation with the key.

Object.keys(obj).forEach(function(k){
    console.log(k + ' - ' + obj[k]);
});

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them).

Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity.

The following code runs as expected, even in a console application:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

How might I schedule a C# Windows Service to perform a task daily?

Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.

How to replace special characters in a string?

Following the example of the Andrzej Doyle's answer, I think the better solution is to use org.apache.commons.lang3.StringUtils.stripAccents():

package bla.bla.utility;

import org.apache.commons.lang3.StringUtils;

public class UriUtility {
    public static String normalizeUri(String s) {
        String r = StringUtils.stripAccents(s);
        r = r.replace(" ", "_");
        r = r.replaceAll("[^\\.A-Za-z0-9_]", "");
        return r;
    }
}

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests or any other class that extends AbstractSpringContextTests), you can access the app context by calling the getContext() method.
Check out the javadocs for the package org.springframework.test.

How to set background color in jquery

Try this for multiple CSS styles:

$(this).css({
    "background-color": 'red',
    "color" : "white"
});

Node.js Web Application examples/tutorials

I would suggest you check out the various tutorials that are coming out lately. My current fav is:

http://nodetuts.com/

Hope this helps.

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100)) 

to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

Importing a Maven project into Eclipse from Git


Step 1 : Setting Up Eclipse

First of all you'll need to have a few Eclipse plug-ins installed. So use eclipse IDE software install feature in the help dropdown menu ? Install new software, and add link to Available Software Site, then install it.

  1. GIT plugin (EGIT)- http://download.eclipse.org/egit/updates
  2. Eclipse Maven plugin (M2Eclipse) - http://download.eclipse.org/technology/m2e/releases
  3. Maven SCM Handler for EGit (m2e-egit)

    Install from the M2E Marketplace (Settings ? Maven ? Discovery ? Open Catalog and search for " m2e-egit")


Step 2 : Clone the repository

Clone(download) your Maven Projects from Git

Check out non-eclipse Maven Projects from Git (File ? Import.. ? Maven ? Check out Maven Projects from SCM)

File ? Import.. ? Maven ? Check out Maven Projects from SCM

Now add your git repository link to SCM URI field.Then click next & finish.

Python pip install module is not found. How to link python to pip location?

Here is something I learnt after a long time of having issues with pip when I had several versions of Python installed (valid especially for OS X users which are probably using brew to install python blends.)

I assume that most python developers do have at the beginning of their scripts:

#!/bin/env python

You may be surprised to find out that this is not necessarily the same python as the one you run from the command line >python

To be sure you install the package using the correct pip instance for your python interpreter you need to run something like:

>/bin/env python -m pip install --upgrade mymodule

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

Adding a collaborator to my free GitHub account?

Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.

Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.

Printing 1 to 1000 without loop or conditionals

Should work on any machine that doesn't like 0 / 0. You could replace this with a null pointer reference if you need to. The program can fail after printing 1 to 1000, right?

#include <stdio.h>

void print_1000(int i);
void print_1000(int i) {
    int j;
    printf("%d\n", i);
    j = 1000 - i;
    j = j / j;
    i++;
    print_1000(i);
}

int main() {
    print_1000(1);
}

Serving favicon.ico in ASP.NET MVC

Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:

<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>

You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:

<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->

Remove warning messages in PHP

If you don't want to show warnings as well as errors use

// Turn off all error reporting
error_reporting(0);

Error Reporting - PHP Manual

My Routes are Returning a 404, How can I Fix Them?

Have you tried to check if

http://localhost/mysite/public/index.php/user 

was working? If so then make sure all your path's folders don't have any uppercase letters. I had the same situation and converting letters to lower case helped.

React Native: Getting the position of an element

React Native provides a .measure(...) method which takes a callback and calls it with the offsets and width/height of a component:

myComponent.measure( (fx, fy, width, height, px, py) => {

    console.log('Component width is: ' + width)
    console.log('Component height is: ' + height)
    console.log('X offset to frame: ' + fx)
    console.log('Y offset to frame: ' + fy)
    console.log('X offset to page: ' + px)
    console.log('Y offset to page: ' + py)
})

Example...

The following calculates the layout of a custom component after it is rendered:

class MyComponent extends React.Component {
    render() {
        return <View ref={view => { this.myComponent = view; }} />
    }
    componentDidMount() {
        // Print component dimensions to console
        this.myComponent.measure( (fx, fy, width, height, px, py) => {
            console.log('Component width is: ' + width)
            console.log('Component height is: ' + height)
            console.log('X offset to frame: ' + fx)
            console.log('Y offset to frame: ' + fy)
            console.log('X offset to page: ' + px)
            console.log('Y offset to page: ' + py)
        })        
    }
}

Bug notes

  • Note that sometimes the component does not finish rendering before componentDidMount() is called. If you are getting zeros as a result from measure(...), then wrapping it in a setTimeout should solve the problem, i.e.:

    setTimeout( myComponent.measure(...), 0 )
    

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>

...and:

@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */
}

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */
}

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

How to get current memory usage in android?

final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

It is a strange code. It return MaxMemory - (totalMemory - freeMemory). If freeMemory equals 0, then the code will return MaxMemory - totalMemory, so it can more or equals 0. Why freeMemory not used?

SQL Server : SUM() of multiple rows including where clauses

The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

How to pass multiple parameters in json format to a web service using jquery?

This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:

data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"

Make sure your JSON is properly formed?

How do I give PHP write access to a directory?

Best way in giving write access to a directory..

$dst = "path/to/directory";
mkdir($dst); 
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

'dict' object has no attribute 'has_key'

I think it is considered "more pythonic" to just use in when determining if a key already exists, as in

if start not in graph:
    return None

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

UIAlertView first deprecated IOS 9

Check this:

UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:@"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera =[UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self Action];  //call Action need to perform 
    }];

[alertctrl addAction:camera];
-(void)Action 

{

}

HTML not loading CSS file

Check both files in the same directory and then try this

<link href="style.css" rel="stylesheet" type="text/css"/>

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

How to create a session using JavaScript?

I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.

Is it impossible to assign session values directly through javascript? No, there is a way to do that.

Look again your code:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

A little bit change:

<script type="text/javascript" >
{
  <%Session["controlID"] = "This is my session";%>
}
</script>

The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?

Let change a little bit more:

<script type="text/javascript" >
{
  var strTest = "This is my session"; 
  <%Session["controlID"] = "'+ strTest +'";%>
}
</script>

The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:

<%Session["controlID"] = strTest;%>

Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.

Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:

<script type="text/javascript" >
{
 var strTest = "This is my session"; 
 PageMethods.CreateSessionViaJavascript(strTest);
}
</script> 

In code-behind page. I create a WebMethod:

[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
    Page objp = new Page();
    objp.Session["controlID"] = strTest; 
    return strTest;
}

After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".

If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

Source: JavaScript - How to Set values to Session in Javascript

Happy codding, Tri

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

How and where to use ::ng-deep?

Make sure not to miss the explanation of :host-context which is directly above ::ng-deep in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.

::ng-deep is often necessary when you didn't write the component and don't have access to its source, but :host-context can be a very useful option when you do.

For example I have a black <h1> header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.

If I didn't have access to the source I may have to do this in the css for the parent:

.theme-dark widget-box ::ng-deep h1 { color: white; }

But instead with :host-context you can do this inside the component.

 h1 
 {
     color: black;       // default color

     :host-context(.theme-dark) &
     {
         color: white;   // color for dark-theme
     }

     // OR set an attribute 'outside' with [attr.theme]="'dark'"

     :host-context([theme='dark']) &
     {
         color: white;   // color for dark-theme
     }
 }

This will look anywhere in the component chain for .theme-dark and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep which while often necessary is somewhat of an anti-pattern.

In this case the & is replaced by the h1 (that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.

Be careful to get the correct number of :. For ::ng-deep there are two and for :host-context only one.

Plotting in a non-blocking way with Matplotlib

I figured out that the plt.pause(0.001) command is the only thing needed and nothing else.

plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.

Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.

The documentation of the plt.pause(interval) command states:

If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.

and this is pretty much exactly what we want. Try this code:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 51)               # x coordinates  
         
for z in range(10, 50):

    y = np.power(x, z/10)          # y coordinates of plot for animation

    plt.cla()                      # delete previous plot
    plt.axis([-50, 50, 0, 10000])  # set axis limits, to avoid rescaling
    plt.plot(x, y)                 # generate new plot
    plt.pause(0.1)                 # pause 0.1 sec, to force a plot redraw

How to Set Focus on JTextField?

if is there only one Top-Level Container then last lines in GUI constructor would be for example

.
.
.
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

How do I find the index of a character within a string in C?

void myFunc(char* str, char c)
{
    char* ptr;
    int index;

    ptr = strchr(str, c);
    if (ptr == NULL)
    {
        printf("Character not found\n");
        return;
    }

    index = ptr - str;

    printf("The index is %d\n", index);
    ASSERT(str[index] == c);  // Verify that the character at index is the one we want.
}

This code is currently untested, but it demonstrates the proper concept.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Get startup type of Windows service using PowerShell

If you update to PowerShell 5 you can query all of the services on the machine and display Name and StartType and sort it by StartType for easy viewing:

Get-Service |Select-Object -Property Name,StartType |Sort-Object -Property StartType

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How do I pass an object from one activity to another on Android?

This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,

class Myclass    {
  int a;
  class SubClass    {
       int b;
  }
}

With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,

MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String

Now you can pass this String across activities as a StringExtra with the activity intent.

Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);

Then in the receiving activity, create the original object from the string representation.

String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object

It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.

UPDATE


While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.

  1. Eventbus
  2. Otto

How can I get a precise time, for example in milliseconds in Objective-C?

Please do not use NSDate, CFAbsoluteTimeGetCurrent, or gettimeofday to measure elapsed time. These all depend on the system clock, which can change at any time due to many different reasons, such as network time sync (NTP) updating the clock (happens often to adjust for drift), DST adjustments, leap seconds, and so on.

This means that if you're measuring your download or upload speed, you will get sudden spikes or drops in your numbers that don't correlate with what actually happened; your performance tests will have weird incorrect outliers; and your manual timers will trigger after incorrect durations. Time might even go backwards, and you end up with negative deltas, and you can end up with infinite recursion or dead code (yeah, I've done both of these).

Use mach_absolute_time. It measures real seconds since the kernel was booted. It is monotonically increasing (will never go backwards), and is unaffected by date and time settings. Since it's a pain to work with, here's a simple wrapper that gives you NSTimeIntervals:

// LBClock.h
@interface LBClock : NSObject
+ (instancetype)sharedClock;
// since device boot or something. Monotonically increasing, unaffected by date and time settings
- (NSTimeInterval)absoluteTime;

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute;
@end

// LBClock.m
#include <mach/mach.h>
#include <mach/mach_time.h>

@implementation LBClock
{
    mach_timebase_info_data_t _clock_timebase;
}

+ (instancetype)sharedClock
{
    static LBClock *g;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g = [LBClock new];
    });
    return g;
}

- (id)init
{
    if(!(self = [super init]))
        return nil;
    mach_timebase_info(&_clock_timebase);
    return self;
}

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute
{
    uint64_t nanos = (machAbsolute * _clock_timebase.numer) / _clock_timebase.denom;

    return nanos/1.0e9;
}

- (NSTimeInterval)absoluteTime
{
    uint64_t machtime = mach_absolute_time();
    return [self machAbsoluteToTimeInterval:machtime];
}
@end

How does one output bold text in Bash?

I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.

First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:

echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

Filter by process/PID in Wireshark

If you want to follow an application that still has to be started then it's certainly possible:

  1. Install docker (see https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/)
  2. Open a terminal and run a tiny container: docker run -t -i ubuntu /bin/bash (change "ubuntu" to your favorite distro, this doesn't have to be the same as in your real system)
  3. Install your application in the container using the same way that you would install it in a real system.
  4. Start wireshark in your real system, go to capture > options . In the window that will open you'll see all your interfaces. Instead of choosing any, wlan0, eth0, ... choose the new virtual interface docker0 instead.
  5. Start capturing
  6. Start your application in the container

You might have some doubts about running your software in a container, so here are the answers to the questions you probably want to ask:

  • Will my application work inside a container ? Almost certainly yes, but you might need to learn a bit about docker to get it working
  • Won't my application run slow ? Negligible. If your program is something that runs heavy calculations for a week then it might now take a week and 3 seconds
  • What if my software or something else breaks in the container ? That's the nice thing about containers. Whatever is running inside can only break the current container and can't hurt the rest of the system.

Convert negative data into positive data in SQL Server

An easy and straightforward solution using the CASE function:

SELECT CASE WHEN ( a > 0 ) THEN (a*-1) ELSE (a*-1) END AS NegativeA,
       CASE WHEN ( b > 0 ) THEN (b*-1) ELSE (b*-1) END AS PositiveB
FROM YourTableName

How can I count text lines inside an DOM element? Can I?

You can compare element height and element height with line-height: 0

function lineCount(elm) {
  const style = elm.getAttribute('style')
  elm.style.marginTop = 0
  elm.style.marginBottom = 0
  elm.style.paddingTop = 0
  elm.style.paddingBottom = 0
  const heightAllLine = elm.offsetHeight
  elm.style.lineHeight = 0
  const height1line = elm.offsetHeight
  const lineCount = Math.round(heightAllLine / height1line)
  elm.setAttribute('style', style)
  if (isNaN(lineCount)) return 0
  return lineCount
}

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

Passing string to a function in C - with or without pointers?

Assuming that you meant to write

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

Change Image of ImageView programmatically in Android

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

What is the Simplest Way to Reverse an ArrayList?

ArrayList<Integer> myArray = new ArrayList<Integer>();

myArray.add(1);
myArray.add(2);
myArray.add(3);

int reverseArrayCounter = myArray.size() - 1;

for (int i = reverseArrayCounter; i >= 0; i--) {
    System.out.println(myArray.get(i));
}

Reference an Element in a List of Tuples

You can get a list of the first element in each tuple using a list comprehension:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']

What is the purpose of Android's <merge> tag in XML layouts?

The include tag

The <include> tag lets you to divide your layout into multiple files: it helps dealing with complex or overlong user interface.

Let's suppose you split your complex layout using two include files as follows:

top_level_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <include layout="@layout/include1.xml" />

    <!-- Second include file -->
    <include layout="@layout/include2.xml" />

</LinearLayout>

Then you need to write include1.xml and include2.xml.

Keep in mind that the xml from the include files is simply dumped in your top_level_activity layout at rendering time (pretty much like the #INCLUDE macro for C).

The include files are plain jane layout xml.

include1.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:text="First include"
    android:textAppearance="?android:attr/textAppearanceMedium"/>

... and include2.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button1"
    android:text="Button" />

See? Nothing fancy. Note that you still have to declare the android namespace with xmlns:android="http://schemas.android.com/apk/res/android.

So the rendered version of top_level_activity.xml is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <TextView
        android:id="@+id/textView1"
        android:text="First include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />


</LinearLayout>

In your java code, all this is transparent: findViewById(R.id.textView1) in your activity class returns the correct widget ( even if that widget was declared in a xml file different from the activity layout).

And the cherry on top: the visual editor handles the thing swimmingly. The top level layout is rendered with the xml included.

The plot thickens

As an include file is a classic layout xml file, it means that it must have one top element. So in case your file needs to include more than one widget, you would have to use a layout.

Let's say that include1.xml has now two TextView: a layout has to be declared. Let's choose a LinearLayout.

include1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout2" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</LinearLayout>

The top_level_activity.xml will be rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <LinearLayout 
        android:id="@+id/layout2" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

       <TextView
            android:id="@+id/textView1"
            android:text="Second include"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

       <TextView
            android:id="@+id/textView2"
            android:text="More text"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

   </LinearLayout>

     <!-- Second include file -->
   <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

But wait the two levels of LinearLayout are redundant!

Indeed, the two nested LinearLayout serve no purpose as the two TextView could be included under layout1for exactly the same rendering.

So what can we do?

Enter the merge tag

The <merge> tag is just a dummy tag that provides a top level element to deal with this kind of redundancy issues.

Now include1.xml becomes:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</merge>

and now top_level_activity.xml is rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file --> 
    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

You saved one hierarchy level, avoid one useless view: Romain Guy sleeps better already.

Aren't you happier now?

Determining image file size + dimensions via Javascript?

The only thing you can do is to upload the image to a server and check the image size and dimension using some server side language like C#.

Edit:

Your need can't be done using javascript only.

"Could not find or load main class" Error while running java program using cmd prompt

I faced the same problem and tried everything mentioned here. The thing was I didn't refresh my project in eclipse after class creation . And once I refreshed it things worked as expected.

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

VBA: Convert Text to Number

Using aLearningLady's answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.

The below code worked for me.

Dim lastrow as Integer

lastrow = Cells(Rows.Count, 2).End(xlUp).Row

Range("C2:C" & lastrow).Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

Does React Native styles support gradients?

First, run npm install expo-linear-gradient --save

You don't need to use an animated tag, but this is what I was using in my code.

inside colors={[ put your gradient colors ]}

then you can use something like this:

 import { LinearGradient } from "expo-linear-gradient";
 import { Animated } from "react-native";

 <AnimatedLinearGradient
    colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
    style={{ your styles go here }}/>

const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);

ExpressJS - throw er Unhandled error event

I fixed the bug by changing the port which was

app.set('port', process.env.PORT || 3000);<br>

and changed to:

app.set('port', process.env.PORT || 8080);<br>

JavaScript URL Decode function

//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));

PHPUnit assert that an exception was thrown?

For PHPUnit 5.7.27 and PHP 5.6 and to test multiple exceptions in one test, it was important to force the exception testing. Using exception handling alone to assert the instance of Exception will skip testing the situation if no exception occurs.

public function testSomeFunction() {

    $e=null;
    $targetClassObj= new TargetClass();
    try {
        $targetClassObj->doSomething();
    } catch ( \Exception $e ) {
    }
    $this->assertInstanceOf(\Exception::class,$e);
    $this->assertEquals('Some message',$e->getMessage());

    $e=null;
    try {
        $targetClassObj->doSomethingElse();
    } catch ( Exception $e ) {
    }
    $this->assertInstanceOf(\Exception::class,$e);
    $this->assertEquals('Another message',$e->getMessage());

}

How do you push just a single Git branch (and no other branches)?

By default git push updates all the remote branches. But you can configure git to update only the current branch to it's upstream.

git config push.default upstream

It means git will update only the current (checked out) branch when you do git push.

Other valid options are:

  • nothing : Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
  • matching : Push all branches having the same name on both ends. (default option prior to Ver 1.7.11)
  • upstream: Push the current branch to its upstream branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.
  • tracking : Deprecated, use upstream instead.
  • current : Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.
  • simple : [available since Ver 1.7.11] in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

List<Map<String, String>> vs List<? extends Map<String, String>>

You cannot assign expressions with types such as List<NavigableMap<String,String>> to the first.

(If you want to know why you can't assign List<String> to List<Object> see a zillion other questions on SO.)

What's the best way to calculate the size of a directory in .NET?

To improve the performance, you could use the Task Parallel Library (TPL). Here is a good sample: Directory file size calculation - how to make it faster?

I didn't test it, but the author says it is 3 times faster than a non-multithreaded method...

Basic Ajax send/receive with node.js

Here is a fully functional example of what you are trying to accomplish. I created the example inside of hyperdev rather than jsFiddle so that you could see the server-side and client-side code.

View Code: https://hyperdev.com/#!/project/destiny-authorization

View Working Application: https://destiny-authorization.hyperdev.space/

This code creates a handler for a get request that returns a random string:

app.get("/string", function(req, res) {
    var strings = ["string1", "string2", "string3"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
});

This jQuery code then makes the ajax request and receives the random string from the server.

$.get("/string", function(string) {
  $('#txtString').val(string);
});

Note that this example is based on code from Jamund Ferguson's answer so if you find this useful be sure to upvote him as well. I just thought this example would help you to see how everything fits together.

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

For a checkbox, you don't need to subclass the UIButton. It already has the isSelected property to handle this.

checkbox = UIButton.init(type: .custom)
checkbox.setImage(UIImage.init(named: "iconCheckboxOutlined"), for: .normal)
checkbox.setImage(UIImage.init(named: "iconCheckboxFilled"), for: .selected)
checkbox.addTarget(self, action: #selector(self.toggleCheckboxSelection), for: .touchUpInside)

Then in the action method toggle it's isSelected state.

@objc func toggleCheckboxSelection() {
    checkbox.isSelected = !checkbox.isSelected
}

Check if object value exists within a Javascript array of objects and if not add a new object to array

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

_x000D_
_x000D_
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];_x000D_
_x000D_
function add(arr, name) {_x000D_
  const { length } = arr;_x000D_
  const id = length + 1;_x000D_
  const found = arr.some(el => el.username === name);_x000D_
  if (!found) arr.push({ id, username: name });_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
console.log(add(arr, 'ted'));
_x000D_
_x000D_
_x000D_

Jump to function definition in vim

If everything is contained in one file, there's the command gd (as in 'goto definition'), which will take you to the first occurrence in the file of the word under the cursor, which is often the definition.

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Beside all the above hints like track by and smaller loops, this one also helped me a lot

<span ng-bind="::stock.name"></span>

this piece of code would print the name once it has been loaded, and stop watching it after that. Similarly, for ng-repeats, it could be used as

<div ng-repeat="stock in ::ctrl.stocks">{{::stock.name}}</div>

however it only works for AngularJS version 1.3 and higher. From http://www.befundoo.com/blog/optimizing-ng-repeat-in-angularjs/

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

C#: Dynamic runtime cast

Try a generic:

public static T CastTo<T>(this dynamic obj, bool safeCast) where T:class
{
   try
   {
      return (T)obj;
   }
   catch
   {
      if(safeCast) return null;
      else throw;
   }
}

This is in extension method format, so its usage would be as if it were a member of dynamic objects:

dynamic myDynamic = new Something();
var typedObject = myDynamic.CastTo<Something>(false);

EDIT: Grr, didn't see that. Yes, you could reflectively close the generic, and it wouldn't be hard to hide in a non-generic extension method:

public static dynamic DynamicCastTo(this dynamic obj, Type castTo, bool safeCast)
{
   MethodInfo castMethod = this.GetType().GetMethod("CastTo").MakeGenericMethod(castTo);
   return castMethod.Invoke(null, new object[] { obj, safeCast });
}

I'm just not sure what you'd get out of this. Basically you're taking a dynamic, forcing a cast to a reflected type, then stuffing it back in a dynamic. Maybe you're right, I shouldn't ask. But, this'll probably do what you want. Basically when you go into dynamic-land, you lose the need to perform most casting operations as you can discover what an object is and does through reflective methods or trial and error, so there aren't many elegant ways to do this.

Using request.setAttribute in a JSP page

If you want your requests to persists try this:

example: on your JSP or servlet page

request.getSession().setAttribute("SUBFAMILY", subFam);

and on any receiving page use the below lines to retrieve your session and data:

SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");

Boolean Field in Oracle

The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as CHAR for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)

Advantages of 0/1:

  • Language independent. 'Y' and 'N' would be fine if everyone used it. But they don't. In France they use 'O' and 'N' (I have seen this with my own eyes). I haven't programmed in Finland to see whether they use 'E' and 'K' there - no doubt they're smarter than that, but you can't be sure.
  • Congruent with practice in widely-used programming languages (C, C++, Perl, Javascript)
  • Plays better with the application layer e.g. Hibernate
  • Leads to more succinct SQL, for example, to find out how many bananas are ready to eat select sum(is_ripe) from bananas instead of select count(*) from bananas where is_ripe = 'Y' or even (yuk) select sum(case is_ripe when 'Y' then 1 else 0) from bananas

Advantages of 'Y'/'N':

  • Takes up less space than 0/1
  • It's what Oracle suggests, so might be what some people are more used to

Another poster suggested 'Y'/null for performance gains. If you've proven that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (some_column is null instead of some_column = 0) and in a left join you'll conflate falseness with nonexistent records.

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

How to resolve git stash conflict without commit?

The fastest way I have found is to resolve the conflict, then do git add -u, and then do git reset HEAD, that doesn't even involve a commit.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

simple way to display data in a .txt file on a webpage?

That's the code I use:

<?php   
    $path="C:/foopath/";
    $file="foofile.txt";

    //read file contents
    $content="
        <h2>$file</h2>
            <code>
                <pre>".htmlspecialchars(file_get_contents("$path/$file"))."</pre>
            </code>";

    //display
    echo $content;
?>

Keep in mind that if the user can modify $path or $file (for example via $_GET or $_POST), he/she will be able to see all your source files (danger!)

How to check if a Docker image with a specific tag exist locally?

You can use like the following:

[ ! -z $(docker images -q someimage:sometag) ] || echo "does not exist"

Or:

[ -z $(docker images -q someimage:sometag) ] || echo "already exists"

Wait some seconds without blocking UI execution

i really disadvise you against using Thread.Sleep(2000), because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.

I recommend to use a C# Timer instead of Thread.Sleep(). Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); method.

How to compare two date values with jQuery

Once you are able to parse those strings into a Date object comparing them is easy (Using the < operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.

Converting ArrayList to HashMap

The general methodology would be to iterate through the ArrayList, and insert the values into the HashMap. An example is as follows:

HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
   productMap.put(product.getProductCode(), product);
}

Can you animate a height change on a UITableViewCell when selected?

just a note for someone like me searching for add "More Details" on custom cell.

[tableView beginUpdates];
[tableView endUpdates];

Did a excellent work, but don't forget to "crop" cell view. From Interface Builder select your Cell -> Content View -> from Property Inspector select "Clip subview"

How do I set up Android Studio to work completely offline?

Not sure if it was removed before, I heard it was kinda buggy in 0.5.8 but in AS 0.5.9 the settings is there:

Gradle > Global Gradle settings > Offline work

What is correct content-type for excel files?

Do keep in mind that the file.getContentType could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.

android - setting LayoutParams programmatically

  LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                   /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*weight*/ 1.0f
            );
            YOUR_VIEW.setLayoutParams(param);

np.mean() vs np.average() in Python NumPy?

In your invocation, the two functions are the same.

average can compute a weighted average though.

Doc links: mean and average

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

Django Admin - change header 'Django administration' text

You can use these following lines in your main urls.py

you can add the text in the quotes to be displayed

To replace the text Django admin use admin.site.site_header = ""

To replace the text Site Administration use admin.site.site_title = ""

To replace the site name you can use admin.site.index_title = ""

To replace the url of the view site button you can use admin.site.site_url = ""

How to use BigInteger?

Yes it's Immutable

sum.add(BigInteger.valueOf(i));

so the method add() of BigInteger class does not add new BigIntger value to its own value ,but creates and returns a new BigInteger reference without changing the current BigInteger and this is what done even in the case of Strings

Throw HttpResponseException or return Request.CreateErrorResponse?

The approach I have taken is to just throw exceptions from the api controller actions and have an exception filter registered that processes the exception and sets an appropriate response on the action execution context.

The filter exposes a fluent interface that provides a means of registering handlers for specific types of exceptions prior to registering the filter with global configuration.

The use of this filter enables centralized exception handling instead of spreading it across the controller actions. There are however cases where I will catch exceptions within the controller action and return a specific response if it does not make sense to centralize the handling of that particular exception.

Example registration of filter:

GlobalConfiguration.Configuration.Filters.Add(
    new UnhandledExceptionFilterAttribute()
    .Register<KeyNotFoundException>(HttpStatusCode.NotFound)

    .Register<SecurityException>(HttpStatusCode.Forbidden)

    .Register<SqlException>(
        (exception, request) =>
        {
            var sqlException = exception as SqlException;

            if (sqlException.Number > 50000)
            {
                var response            = request.CreateResponse(HttpStatusCode.BadRequest);
                response.ReasonPhrase   = sqlException.Message.Replace(Environment.NewLine, String.Empty);

                return response;
            }
            else
            {
                return request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }
    )
);

UnhandledExceptionFilterAttribute class:

using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;

namespace Sample
{
    /// <summary>
    /// Represents the an attribute that provides a filter for unhandled exceptions.
    /// </summary>
    public class UnhandledExceptionFilterAttribute : ExceptionFilterAttribute
    {
        #region UnhandledExceptionFilterAttribute()
        /// <summary>
        /// Initializes a new instance of the <see cref="UnhandledExceptionFilterAttribute"/> class.
        /// </summary>
        public UnhandledExceptionFilterAttribute() : base()
        {

        }
        #endregion

        #region DefaultHandler
        /// <summary>
        /// Gets a delegate method that returns an <see cref="HttpResponseMessage"/> 
        /// that describes the supplied exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, HttpRequestMessage, HttpResponseMessage}"/> delegate method that returns 
        /// an <see cref="HttpResponseMessage"/> that describes the supplied exception.
        /// </value>
        private static Func<Exception, HttpRequestMessage, HttpResponseMessage> DefaultHandler = (exception, request) =>
        {
            if(exception == null)
            {
                return null;
            }

            var response            = request.CreateResponse<string>(
                HttpStatusCode.InternalServerError, GetContentOf(exception)
            );
            response.ReasonPhrase   = exception.Message.Replace(Environment.NewLine, String.Empty);

            return response;
        };
        #endregion

        #region GetContentOf
        /// <summary>
        /// Gets a delegate method that extracts information from the specified exception.
        /// </summary>
        /// <value>
        /// A <see cref="Func{Exception, String}"/> delegate method that extracts information 
        /// from the specified exception.
        /// </value>
        private static Func<Exception, string> GetContentOf = (exception) =>
        {
            if (exception == null)
            {
                return String.Empty;
            }

            var result  = new StringBuilder();

            result.AppendLine(exception.Message);
            result.AppendLine();

            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                result.AppendLine(innerException.Message);
                result.AppendLine();
                innerException = innerException.InnerException;
            }

            #if DEBUG
            result.AppendLine(exception.StackTrace);
            #endif

            return result.ToString();
        };
        #endregion

        #region Handlers
        /// <summary>
        /// Gets the exception handlers registered with this filter.
        /// </summary>
        /// <value>
        /// A <see cref="ConcurrentDictionary{Type, Tuple}"/> collection that contains 
        /// the exception handlers registered with this filter.
        /// </value>
        protected ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> Handlers
        {
            get
            {
                return _filterHandlers;
            }
        }
        private readonly ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> _filterHandlers = new ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>>();
        #endregion

        #region OnException(HttpActionExecutedContext actionExecutedContext)
        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if(actionExecutedContext == null || actionExecutedContext.Exception == null)
            {
                return;
            }

            var type    = actionExecutedContext.Exception.GetType();

            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;

            if (this.Handlers.TryGetValue(type, out registration))
            {
                var statusCode  = registration.Item1;
                var handler     = registration.Item2;

                var response    = handler(
                    actionExecutedContext.Exception.GetBaseException(), 
                    actionExecutedContext.Request
                );

                // Use registered status code if available
                if (statusCode.HasValue)
                {
                    response.StatusCode = statusCode.Value;
                }

                actionExecutedContext.Response  = response;
            }
            else
            {
                // If no exception handler registered for the exception type, fallback to default handler
                actionExecutedContext.Response  = DefaultHandler(
                    actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
                );
            }
        }
        #endregion

        #region Register<TException>(HttpStatusCode statusCode)
        /// <summary>
        /// Registers an exception handler that returns the specified status code for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register a handler for.</typeparam>
        /// <param name="statusCode">The HTTP status code to return for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler has been added.
        /// </returns>
        public UnhandledExceptionFilterAttribute Register<TException>(HttpStatusCode statusCode) 
            where TException : Exception
        {

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                statusCode, DefaultHandler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
        /// <summary>
        /// Registers the specified exception <paramref name="handler"/> for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to register the <paramref name="handler"/> for.</typeparam>
        /// <param name="handler">The exception handler responsible for exceptions of type <typeparamref name="TException"/>.</param>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception <paramref name="handler"/> 
        /// has been added.
        /// </returns>
        /// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <see langword="null"/>.</exception>
        public UnhandledExceptionFilterAttribute Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler) 
            where TException : Exception
        {
            if(handler == null)
            {
              throw new ArgumentNullException("handler");
            }

            var type    = typeof(TException);
            var item    = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
                null, handler
            );

            if (!this.Handlers.TryAdd(type, item))
            {
                Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;

                if (this.Handlers.TryRemove(type, out oldItem))
                {
                    this.Handlers.TryAdd(type, item);
                }
            }

            return this;
        }
        #endregion

        #region Unregister<TException>()
        /// <summary>
        /// Unregisters the exception handler for exceptions of type <typeparamref name="TException"/>.
        /// </summary>
        /// <typeparam name="TException">The type of exception to unregister handlers for.</typeparam>
        /// <returns>
        /// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler 
        /// for exceptions of type <typeparamref name="TException"/> has been removed.
        /// </returns>
        public UnhandledExceptionFilterAttribute Unregister<TException>()
            where TException : Exception
        {
            Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> item = null;

            this.Handlers.TryRemove(typeof(TException), out item);

            return this;
        }
        #endregion
    }
}

Source code can also be found here.

Check if pull needed in Git

This one-liner works for me in zsh (from @Stephen Haberman's answer)

git fetch; [ $(git rev-parse HEAD) = $(git rev-parse @{u}) ] \
    && echo "Up to date" || echo "Not up to date"

How to insert the current timestamp into MySQL database using a PHP insert query

Instead of NOW() you can use UNIX_TIMESTAMP() also:

$update_query = "UPDATE db.tablename 
                 SET insert_time=UNIX_TIMESTAMP()
                 WHERE username='$somename'";

Difference between UNIX_TIMESTAMP and NOW() in MySQL

builtins.TypeError: must be str, not bytes

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

How do I set the proxy to be used by the JVM

To set an HTTP/HTTPS and/or SOCKS proxy programmatically:

...

public void setProxy() {
    if (isUseHTTPProxy()) {
        // HTTP/HTTPS Proxy
        System.setProperty("http.proxyHost", getHTTPHost());
        System.setProperty("http.proxyPort", getHTTPPort());
        System.setProperty("https.proxyHost", getHTTPHost());
        System.setProperty("https.proxyPort", getHTTPPort());
        if (isUseHTTPAuth()) {
            String encoded = new String(Base64.encodeBase64((getHTTPUsername() + ":" + getHTTPPassword()).getBytes()));
            con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
            Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));
        }
    }
    if (isUseSOCKSProxy()) {
        // SOCKS Proxy
        System.setProperty("socksProxyHost", getSOCKSHost());
        System.setProperty("socksProxyPort", getSOCKSPort());
        if (isUseSOCKSAuth()) {
            System.setProperty("java.net.socks.username", getSOCKSUsername());
            System.setProperty("java.net.socks.password", getSOCKSPassword());
            Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));
        }
    }
}

...

public class ProxyAuth extends Authenticator {
    private PasswordAuthentication auth;

    private ProxyAuth(String user, String password) {
        auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return auth;
    }
}

...

Remember that HTTP proxies and SOCKS proxies operate at different levels in the network stack, so you can use one or the other or both.

How to update values in a specific row in a Python Pandas DataFrame?

So first of all, pandas updates using the index. When an update command does not update anything, check both left-hand side and right-hand side. If you don't update the indices to follow your identification logic, you can do something along the lines of

>>> df.loc[df.filename == 'test2.dat', 'n'] = df2[df2.filename == 'test2.dat'].loc[0]['n']
>>> df
Out[331]: 
    filename   m     n
0  test0.dat  12  None
1  test2.dat  13    16

If you want to do this for the whole table, I suggest a method I believe is superior to the previously mentioned ones: since your identifier is filename, set filename as your index, and then use update() as you wanted to. Both merge and the apply() approach contain unnecessary overhead:

>>> df.set_index('filename', inplace=True)
>>> df2.set_index('filename', inplace=True)
>>> df.update(df2)
>>> df
Out[292]: 
            m     n
filename           
test0.dat  12  None
test2.dat  13    16

Skipping Iterations in Python

Example for Continue:

number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      continue    # continue here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 6 # Note: 5 is skipped!!
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop

How to set a class attribute to a Symfony2 form input

Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.

{# render a field row, but display a label with text "foo" #} {{ form_row(form.name, {'label': 'foo'}) }}

The second argument to form_row() is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above.

See "More about Form Variables" to learn about the variables argument.

How to convert NUM to INT in R?

Use as.integer:

set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819


as.integer(x)
[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

How can Print Preview be called from Javascript?

You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.

That's why your example uses Active X, which bypasses the JavaScript security issues.

So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.

Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

How to return string value from the stored procedure

You are placing your result in the RETURN value instead of in the passed @rvalue.

From MSDN

(RETURN) Is the integer value that is returned. Stored procedures can return an integer value to a calling procedure or an application.

Changing your procedure.

ALTER procedure S_Comp(@str1 varchar(20),@r varchar(100) out) as 

    declare @str2 varchar(100) 
    set @str2 ='welcome to sql server. Sql server is a product of Microsoft' 
    if(PATINDEX('%'+@str1 +'%',@str2)>0) 
        SELECT @r =  @str1+' present in the string' 
    else 
        SELECT @r = @str1+' not present'

Calling the procedure

  DECLARE @r VARCHAR(100)
  EXEC S_Comp 'Test', @r OUTPUT
  SELECT @r

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Access Controller method from another controller in Laravel 5

Here the trait fully emulates running controller by laravel router (including support of middlewares and dependency injection). Tested only with 5.4 version

<?php

namespace App\Traits;

use Illuminate\Pipeline\Pipeline;
use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\SortedMiddleware;

trait RunsAnotherController
{
    public function runController($controller, $method = 'index')
    {
        $middleware = $this->gatherControllerMiddleware($controller, $method);

        $middleware = $this->sortMiddleware($middleware);

        return $response = (new Pipeline(app()))
            ->send(request())
            ->through($middleware)
            ->then(function ($request) use ($controller, $method) {
                return app('router')->prepareResponse(
                    $request, (new ControllerDispatcher(app()))->dispatch(
                    app('router')->current(), $controller, $method
                )
                );
            });
    }

    protected function gatherControllerMiddleware($controller, $method)
    {
        return collect($this->controllerMidlleware($controller, $method))->map(function ($name) {
            return (array)MiddlewareNameResolver::resolve($name, app('router')->getMiddleware(), app('router')->getMiddlewareGroups());
        })->flatten();
    }

    protected function controllerMidlleware($controller, $method)
    {
        return ControllerDispatcher::getMiddleware(
            $controller, $method
        );
    }

    protected function sortMiddleware($middleware)
    {
        return (new SortedMiddleware(app('router')->middlewarePriority, $middleware))->all();
    }
}

Then just add it to your class and run the controller. Note, that dependency injection will be assigned with your current route.

class CustomController extends Controller {
    use RunsAnotherController;

    public function someAction() 
    {
        $controller = app()->make('App\Http\Controllers\AnotherController');

        return $this->runController($controller, 'doSomething');
    }
}

How can I pass a list as a command-line argument with argparse?

TL;DR

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

nargs

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

append

parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567

With append you provide the option multiple times to build up the list.

Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.


Let's take a look in more detail at some of the different ways one might try to do this, and the end result.

import argparse

parser = argparse.ArgumentParser()

# By default it will fail with multiple arguments.
parser.add_argument('--default')

# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)

# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')

# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')

# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)

# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')

# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
    if value is not None:
        print(value)

Here is the output you can expect:

$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ # Quotes won't help here... 
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']

$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Takeaways:

  • Use nargs or action='append'
    • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
    • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
  • Don't use quotes on the command line1
  • Don't use type=list, as it will return a list of lists
    • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
    • You can use type=int (or whatever) to get a list of ints (or whatever)

1: I don't mean in general.. I mean using quotes to pass a list to argparse is not what you want.

How to turn off page breaks in Google Docs?

Turn off "Print Layout" from the "View" menu.

List passed by ref - help me explain this behaviour

You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList aren't seen by TestMethod.

try:

private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);

This then passes a reference to the local-variable myRef (as declared in TestMethod); now, if you reassign the parameter inside ChangeList you are also reassigning the variable inside TestMethod.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

What is the difference between ( for... in ) and ( for... of ) statements?

A see a lot of good answers, but I decide to put my 5 cents just to have good example:

For in loop

iterates over all enumerable props

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
  console.log( key );_x000D_
}
_x000D_
_x000D_
_x000D_

For of loop

iterates over all iterable values

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
  console.log( node.toString() );_x000D_
}
_x000D_
_x000D_
_x000D_

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

In xcode5 from Preferences, Accounts, (select your account), View Details, press refresh button. then select Provision Profile in build settings.

How to select a column name with a space in MySQL

You need to use backtick instead of single quotes:

Single quote - 'Business Name' - Wrong

Backtick - `Business Name` - Correct

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

If you already have it as a DateTime, use:

string x = dt.ToString("yyyy-MM-dd");

See the MSDN documentation for more details. You can specify CultureInfo.InvariantCulture to enforce the use of Western digits etc. This is more important if you're using MMM for the month name and similar things, but it wouldn't be a bad idea to make it explicit:

string x = dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

If you have a string to start with, you'll need to parse it and then reformat... of course, that means you need to know the format of the original string.

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

It seems that your question is quite answered, but i have an approach that may simplify you case:

I had a similar issue trying to return string data from mysql, even configuring both database and php to return strings formatted to utf-8. The only way i got the error was actually returning them from the database.

Finally, sailing through the web i found a really easy way to deal with it:

Giving that you can save all those types of string data in your mysql in different formats and collations, what you only need to do is, right at your php connection file, set the collation to utf-8, like this:

$connection = new mysqli($server, $user, $pass, $db);
$connection->set_charset("utf8");

Wich means that first you save the data in any format or collation and you convert it only at the return to your php file.

Hope it was helpful!

How do I declare a 2d array in C++ using new?

int** ary = new int[sizeY][sizeX]

should be:

int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
    ary[i] = new int[sizeX];
}

and then clean up would be:

for(int i = 0; i < sizeY; ++i) {
    delete [] ary[i];
}
delete [] ary;

EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:

int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

Can I start the iPhone simulator without "Build and Run"?

This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.

Failed to instantiate module error in Angular js

Such error happens when,

1. You misspell module name which you injected.
2. If you missed to include js file of that module.

Sometimes people write js file name instead of the module name which we are injecting.

In these cases what happens is angular tries to look for the module provided in the square bracket []. If it doesn't find the module, it throws error.

NGINX - No input file specified. - php Fast/CGI

use in windows

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

wasn't putting -b

php-cgi.exe -b 127.0.0.1:9000

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
{
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
    {
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
        {
            dirSearch.Filter = getGroupsFilterForDn;
            dirSearch.PropertiesToLoad.Add("name");

            using (var results = dirSearch.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    if (result.Properties.Contains("name"))
                        groups.Add((string)result.Properties["name"][0]);
                }
            }
        }
    }

    return groups;
}

How to get current domain name in ASP.NET

Here is a quick easy way to just get the name of the url.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

How do you add Boost libraries in CMakeLists.txt?

You can use find_package to search for available boost libraries. It defers searching for Boost to FindBoost.cmake, which is default installed with CMake.

Upon finding Boost, the find_package() call will have filled many variables (check the reference for FindBoost.cmake). Among these are BOOST_INCLUDE_DIRS, Boost_LIBRARIES and Boost_XXX_LIBRARY variabels, with XXX replaced with specific Boost libraries. You can use these to specify include_directories and target_link_libraries.

For example, suppose you would need boost::program_options and boost::regex, you would do something like:

find_package( Boost REQUIRED COMPONENTS program_options regex )
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable( run main.cpp ) # Example application based on main.cpp

# Alternatively you could use ${Boost_LIBRARIES} here.
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )

Some general tips:

  • When searching, FindBoost checks the environment variable $ENV{BOOST_ROOT}. You can set this variable before calling find_package if necessary.
  • When you have multiple build-versions of boost (multi-threaded, static, shared, etc.) you can specify you desired configuration before calling find_package. Do this by setting some of the following variables to On: Boost_USE_STATIC_LIBS, Boost_USE_MULTITHREADED, Boost_USE_STATIC_RUNTIME
  • When searching for Boost on Windows, take care with the auto-linking. Read the "NOTE for Visual Studio Users" in the reference.
    • My advice is to disable auto-linking and use cmake's dependency handling: add_definitions( -DBOOST_ALL_NO_LIB )
    • In some cases, you may need to explicitly specify that a dynamic Boost is used: add_definitions( -DBOOST_ALL_DYN_LINK )

How to delete files older than X hours

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

Delegation: EventEmitter or Observable in Angular

You can use either:

  1. Behaviour Subject:

BehaviorSubject is a type of subject, a subject is a special type of observable which can act as observable and observer you can subscribe to messages like any other observable and upon subscription, it returns the last value of the subject emitted by the source observable:

Advantage: No Relationship such as parent-child relationship required to pass data between components.

NAV SERVICE

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  private navSubject$ = new BehaviorSubject<number>(0);

  constructor() {  }

  // Event New Item Clicked
  navItemClicked(navItem: number) {
    this.navSubject$.next(number);
  }

 // Allowing Observer component to subscribe emitted data only
  getNavItemClicked$() {
   return this.navSubject$.asObservable();
  }
}

NAVIGATION COMPONENT

@Component({
  selector: 'navbar-list',
  template:`
    <ul>
      <li><a (click)="navItemClicked(1)">Item-1 Clicked</a></li>
      <li><a (click)="navItemClicked(2)">Item-2 Clicked</a></li>
      <li><a (click)="navItemClicked(3)">Item-3 Clicked</a></li>
      <li><a (click)="navItemClicked(4)">Item-4 Clicked</a></li>
    </ul>
})
export class Navigation {
  constructor(private navService:NavService) {}
  navItemClicked(item: number) {
    this.navService.navItemClicked(item);
  }
}

OBSERVING COMPONENT

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  itemClickedSubcription:any

  constructor(private navService:NavService) {}
  ngOnInit() {

    this.itemClickedSubcription = this.navService
                                      .getNavItemClicked$
                                      .subscribe(
                                        item => this.selectedNavItem(item)
                                       );
  }
  selectedNavItem(item: number) {
    this.item = item;
  }

  ngOnDestroy() {
    this.itemClickedSubcription.unsubscribe();
  }
}

Second Approach is Event Delegation in upward direction child -> parent

  1. Using @Input and @Output decorators parent passing data to child component and child notifying parent component

e.g Answered given by @Ashish Sharma.

How do I import a .bak file into Microsoft SQL Server 2012?

You can use the following script if you don't wish to use Wizard;

RESTORE DATABASE myDB
FROM  DISK = N'C:\BackupDB.bak' 
WITH  REPLACE,RECOVERY,  
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',  
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'

Android: making a fullscreen application

just do this in your manifest file in your activity tag

android:theme="@style/Theme.AppCompat.Light.NoActionBar"

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

how to move elasticsearch data from one server to another

The selected answer makes it sound slightly more complex than it is, the following is what you need (install npm first on your system).

npm install -g elasticdump
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=mapping
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=data

You can skip the first elasticdump command for subsequent copies if the mappings remain constant.

I have just done a migration from AWS to Qbox.io with the above without any problems.

More details over at:

https://www.npmjs.com/package/elasticdump

Help page (as of Feb 2016) included for completeness:

elasticdump: Import and export tools for elasticsearch

Usage: elasticdump --input SOURCE --output DESTINATION [OPTIONS]

--input
                    Source location (required)
--input-index
                    Source index and type
                    (default: all, example: index/type)
--output
                    Destination location (required)
--output-index
                    Destination index and type
                    (default: all, example: index/type)
--limit
                    How many objects to move in bulk per operation
                    limit is approximate for file streams
                    (default: 100)
--debug
                    Display the elasticsearch commands being used
                    (default: false)
--type
                    What are we exporting?
                    (default: data, options: [data, mapping])
--delete
                    Delete documents one-by-one from the input as they are
                    moved.  Will not delete the source index
                    (default: false)
--searchBody
                    Preform a partial extract based on search results
                    (when ES is the input,
                    (default: '{"query": { "match_all": {} } }'))
--sourceOnly
                    Output only the json contained within the document _source
                    Normal: {"_index":"","_type":"","_id":"", "_source":{SOURCE}}
                    sourceOnly: {SOURCE}
                    (default: false)
--all
                    Load/store documents from ALL indexes
                    (default: false)
--bulk
                    Leverage elasticsearch Bulk API when writing documents
                    (default: false)
--ignore-errors
                    Will continue the read/write loop on write error
                    (default: false)
--scrollTime
                    Time the nodes will hold the requested search in order.
                    (default: 10m)
--maxSockets
                    How many simultaneous HTTP requests can we process make?
                    (default:
                      5 [node <= v0.10.x] /
                      Infinity [node >= v0.11.x] )
--bulk-mode
                    The mode can be index, delete or update.
                    'index': Add or replace documents on the destination index.
                    'delete': Delete documents on destination index.
                    'update': Use 'doc_as_upsert' option with bulk update API to do partial update.
                    (default: index)
--bulk-use-output-index-name
                    Force use of destination index name (the actual output URL)
                    as destination while bulk writing to ES. Allows
                    leveraging Bulk API copying data inside the same
                    elasticsearch instance.
                    (default: false)
--timeout
                    Integer containing the number of milliseconds to wait for
                    a request to respond before aborting the request. Passed
                    directly to the request library. If used in bulk writing,
                    it will result in the entire batch not being written.
                    Mostly used when you don't care too much if you lose some
                    data when importing but rather have speed.
--skip
                    Integer containing the number of rows you wish to skip
                    ahead from the input transport.  When importing a large
                    index, things can go wrong, be it connectivity, crashes,
                    someone forgetting to `screen`, etc.  This allows you
                    to start the dump again from the last known line written
                    (as logged by the `offset` in the output).  Please be
                    advised that since no sorting is specified when the
                    dump is initially created, there's no real way to
                    guarantee that the skipped rows have already been
                    written/parsed.  This is more of an option for when
                    you want to get most data as possible in the index
                    without concern for losing some rows in the process,
                    similar to the `timeout` option.
--inputTransport
                    Provide a custom js file to us as the input transport
--outputTransport
                    Provide a custom js file to us as the output transport
--toLog
                    When using a custom outputTransport, should log lines
                    be appended to the output stream?
                    (default: true, except for `$`)
--help
                    This page

Examples:

# Copy an index from production to staging with mappings:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

# Backup index data to a file:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index_mapping.json \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index.json \
  --type=data

# Backup and index to a gzip using stdout:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=$ \
  | gzip > /data/my_index.json.gz

# Backup ALL indices, then use Bulk API to populate another ES cluster:
elasticdump \
  --all=true \
  --input=http://production-a.es.com:9200/ \
  --output=/data/production.json
elasticdump \
  --bulk=true \
  --input=/data/production.json \
  --output=http://production-b.es.com:9200/

# Backup the results of a query to a file
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=query.json \
  --searchBody '{"query":{"term":{"username": "admin"}}}'

------------------------------------------------------------------------------
Learn more @ https://github.com/taskrabbit/elasticsearch-dump`enter code here`

How to make a simple image upload using Javascript/HTML

Here's a simple example with no jQuery. Use URL.createObjectURL, which

creates a DOMString containing a URL representing the object given in the parameter

Then, you can simply set the src of the image to that url:

_x000D_
_x000D_
window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
      if (this.files && this.files[0]) {
          var img = document.querySelector('img');
          img.onload = () => {
              URL.revokeObjectURL(img.src);  // no longer needed, free memory
          }

          img.src = URL.createObjectURL(this.files[0]); // set src to blob url
      }
  });
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
_x000D_
_x000D_

How can you sort an array without mutating the original array?

Try the following

function sortCopy(arr) { 
  return arr.slice(0).sort();
}

The slice(0) expression creates a copy of the array starting at element 0.

Spring 3 RequestMapping: Get path value

I have a similar problem and I resolved in this way:

@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
        @PathVariable String fileName, @PathVariable String fileExtension,
        HttpServletRequest req, HttpServletResponse response ) throws IOException {
    String fullPath = req.getPathInfo();
    // Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
    // fullPath conentent: /SiteXX/images/argentine/flag.jpg
}

Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.

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

I got this message while trying to commit a fragment using attach to root to true instead of false, like so:

return inflater.inflate(R.layout.fragment_profile, container, true)

After doing:

return inflater.inflate(R.layout.fragment_profile, container, false)

It worked.

How to force HTTPS using a web.config file

You need URL Rewrite module, preferably v2 (I have no v1 installed, so cannot guarantee that it will work there, but it should).

Here is an example of such web.config -- it will force HTTPS for ALL resources (using 301 Permanent Redirect):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

P.S. This particular solution has nothing to do with ASP.NET/PHP or any other technology as it's done using URL rewriting module only -- it is processed at one of the initial/lower levels -- before request gets to the point where your code gets executed.

"The system cannot find the file specified" when running C++ program

I had a same problem and i could fixed it! you should add C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64 for 64 bit system / C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib for 32 bit system in property manager-> Linker-> General->Additional library Directories

maybe it can solve the problem of somebody in the future!

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Using CRON jobs to visit url?

You can use this command:

links https://www.honeymovies.com

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Open a URL in a new tab (and not a new window)

I'm going to agree somewhat with the person who wrote (paraphrased here): "For a link in an existing web page, the browser will always open the link in a new tab if the new page is part of the same web site as the existing web page." For me, at least, this "general rule" works in Chrome, Firefox, Opera, IE, Safari, SeaMonkey, and Konqueror.

Anyway, there is a less complicated way to take advantage of what the other person presented. Assuming we are talking about your own web site ("thissite.com" below), where you want to control what the browser does, then, below, you want "specialpage.htm" to be EMPTY, no HTML at all in it (saves time sending data from the server!).

 var wnd, URL;  //global variables

 //specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
 wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); //get reference to just-opened page
 //if the "general rule" above is true, a new tab should have been opened.
 URL = "http://www.someothersite.com/desiredpage.htm";  //ultimate destination
 setTimeout(gotoURL(),200);  //wait 1/5 of a second; give browser time to create tab/window for empty page


 function gotoURL()
 { wnd.open(URL, "_self");  //replace the blank page, in the tab, with the desired page
   wnd.focus();             //when browser not set to automatically show newly-opened page, this MAY work
 }

Why the switch statement cannot be applied on strings?

in many cases you can avid extra work by pulling the first char from the string and switching on that. may end up having to do a nested switch on charat(1) if your cases start with the same value. anyone reading your code would appreciate a hint though because most would prob just if-else-if

How do I add more members to my ENUM-type column in MySQL?

Your code works for me. Here is my test case:

mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                            |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                       |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

What error are you seeing?

FWIW this would also work:

ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');

I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.

EDIT: Now that I can see your error message:

ERROR 1265 (01000): Data truncated for column 'country' at row 1.

I suspect you have some values in your country column that do not appear in your ENUM. What is the output of the following command?

SELECT DISTINCT country FROM carmake;

ANOTHER EDIT: What is the output of the following command?

SHOW VARIABLES LIKE 'sql_mode';

Is it STRICT_TRANS_TABLES or STRICT_ALL_TABLES? That could lead to an error, rather than the usual warning MySQL would give you in this situation.

YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM. The new ENUM definition only allows 'Sweden' and 'Malaysia'. The table has 'USA', 'India' and several others.

LAST EDIT (MAYBE): I think you're trying to do this:

ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

What are the differences between type() and isinstance()?

According to python documentation here is a statement:

8.15. types — Names for built-in types

Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types.

So isinstance() should be preferred over type().

Facebook Android Generate Key Hash

Great blog post on the subject

Extracting the Key Hash from .p12 key

  1. Open Terminal or Command line and navigate to where your .p12 key is.
  2. Type in: “keytool -v -list -keystore mycert.p12 -storetype pkcs12" where mycert.p12 is the filename of your .p12 key.
  3. Enter keystore password (the one you used when exported .p12 key). 4 . Copy sha1 fingerprint signature bytes text.
  4. The bytes at sha1 fingerprint signature are needed to write the “sha1.bin” file. You can use a hexadecimal editor to paste the bytes you copied. Afterwards, save the file as “sha1.bin”.
  5. Open terminal again and type in: “openssl base64 -in sha1.bin -out base64.txt”.
  6. The resulting “base64.txt” will contain the Key Hash that is needed for Facebook.

Great and simple hexadecimal editor for mac: HexFiend

OpenSSL should be preinstalled on mac, and here is the link for Windows version.

Link

What is the purpose of willSet and didSet in Swift?

These are called Property Observers:

Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/ca/jEUH0.l

I suspect it's to allow for things we would traditionally do with KVO such as data binding with UI elements, or triggering side effects of changing a property, triggering a sync process, background processing, etc, etc.

Set Focus After Last Character in Text Box

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

C++: Print out enum value as text

There has been a discussion here which might help: Is there a simple way to convert C++ enum to string?

UPDATE: Here#s a script for Lua which creates an operator<< for each named enum it encounters. This might need some work to make it work for the less simple cases [1]:

function make_enum_printers(s)
    for n,body in string.gmatch(s,'enum%s+([%w_]+)%s*(%b{})') do
    print('ostream& operator<<(ostream &o,'..n..' n) { switch(n){') 
    for k in string.gmatch(body,"([%w_]+)[^,]*") do
    print('  case '..k..': return o<<"'..k..'";')
    end
    print('  default: return o<<"(invalid value)"; }}')
    end
end

local f=io.open(arg[1],"r")
local s=f:read('*a')
make_enum_printers(s)

Given this input:

enum Errors
{ErrorA=0, ErrorB, ErrorC};

enum Sec {
    X=1,Y=X,foo_bar=X+1,Z
};

It produces:

ostream& operator<<(ostream &o,Errors n) { switch(n){
  case ErrorA: return o<<"ErrorA";
  case ErrorB: return o<<"ErrorB";
  case ErrorC: return o<<"ErrorC";
  default: return o<<"(invalid value)"; }}
ostream& operator<<(ostream &o,Sec n) { switch(n){
  case X: return o<<"X";
  case Y: return o<<"Y";
  case foo_bar: return o<<"foo_bar";
  case Z: return o<<"Z";
  default: return o<<"(invalid value)"; }}

So that's probably a start for you.

[1] enums in different or non-namespace scopes, enums with initializer expressions which contain a komma, etc.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

In-Short Differences are

1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.

2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.

3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.

An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link

http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/

sed edit file in place

If you are replacing the same amount of characters and after carefully reading “In-place” editing of files...

You can also use the redirection operator <> to open the file to read and write:

sed 's/foo/bar/g' file 1<> file

See it live:

$ cat file
hello
i am here                           # see "here"
$ sed 's/here/away/' file 1<> file  # Run the `sed` command
$ cat file
hello
i am away                           # this line is changed now

From Bash Reference Manual ? 3.6.10 Opening File Descriptors for Reading and Writing:

The redirection operator

[n]<>word

causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.

Assign command output to variable in batch file

Okay here some more complex sample for the use of For /F

:: Main
@prompt -$G
    call :REGQUERY  "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"

@goto :EOF

:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\ 
:: for the key and lists its content

    @call :EXEC "REG QUERY  HKCU\%~1"
    @call :EXEC "REG QUERY "HKLM\%~1""

@goto :EOF    

:EXEC
    @set output=

    @for /F "delims=" %%i in ('%~1 2^>nul') do @(
        set output=%%i
    )

    @if not "%output%"=="" (
        echo %1 -^> %output%
    )

@goto :EOF

I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:

  1. the output from the command executed via call :EXEC command is stored in %output%. Batch cmd doesn't cares about scopes so %output% will be also available in the main script.
  2. the @ the beginning is just decoration and there to suppress echoing the command line. You may delete them all and just put some @echo off at the first line is really dislike that. However like this I find debugging much more nice. Decoration Number two is prompt -$G. It's there to make command prompt look like this ->
  3. I use :: instead of rem
  4. the tilde(~) in %~1 is to remove quotes from the first argument
  5. 2^>nul is there to suppress/discard stderr error output. Normally you would do it via 2>nul. Well the ^ the batch escape char is there avoids to early resolving the redirector(>). There's some simulare use a little later in the script: echo %1 -^>... so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.
  6. even if the compare at @if not "%output%"==""looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""-rerun and consider why this doesn't work. ;)

Create a custom callback in JavaScript

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

Example:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

This is the Codepend with full example.

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

How to increase timeout for a single test case in mocha

This worked for me! Couldn't find anything to make it work with before()

describe("When in a long running test", () => {
  it("Should not time out with 2000ms", async () => {
    let service = new SomeService();
    let result = await service.callToLongRunningProcess();
    expect(result).to.be.true;
  }).timeout(10000); // Custom Timeout 
});

Function inside a function.?

X returns (value +3), while Y returns (value*2)

Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56.

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

The solution to both would be to split the code, so that both functions are declared independent of each other:

function x ($y) 
{
  return($y+3);
}

function y ($z)
{
  return ($z*2);
}

This is also a lot more readable.

Reading integers from binary file in Python

Except struct you can also use array module

import array
values = array.array('l') # array of long integers
values.read(fin, 1) # read 1 integer
file_size  = values[0]

CSS strikethrough different color from text?

As of Feb. 2016, CSS 3 has the support mentioned below. Here is a snippet from a WooCommerce's single product page with price discount

/*Price before discount on single product page*/
body.single-product .price del .amount {
color:           hsl(0, 90%, 65%);
font-size:       15px;
text-decoration: line-through;
/*noinspection CssOverwrittenProperties*/
text-decoration: white double line-through; /* Ignored in CSS1/CSS2 UAs */
}

Resulting in: Text decoration example


CSS 3 will likely have direct support using the text-decoration-color property. In particular:

The text-decoration-color CSS property sets the color used when drawing underlines, overlines, or strike-throughs specified by text-decoration-line. This is the preferred way to color these text decorations, rather than using combinations of other HTML elements.

Also see text-decoration-color in the CSS 3 draft spec.

If you want to use this method immediately, you probably have to prefix it, using -moz-text-decoration-color. (Also specify it without -moz-, for forward-compatibility.)

HTML/Javascript Button Click Counter

Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"

<html>
<head>
    <title>Space Clicker</title>
</head>

<body>
    <script type="text/javascript">

    var clicks = 0;
    function hello() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    </script>
    <button type="button" onclick="hello()">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

</body></html>

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

./configure : /bin/sh^M : bad interpreter

Just adding sh before script name make it work in my case.

What's the difference between :: (double colon) and -> (arrow) in PHP?

When the left part is an object instance, you use ->. Otherwise, you use ::.

This means that -> is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while :: is usually used to access static members (though in a few special cases, it's used to access instance members).

In general, :: is used for scope resolution, and it may have either a class name, parent, self, or (in PHP 5.3) static to its left. parent refers to the scope of the superclass of the class where it's used; self refers to the scope of the class where it's used; static refers to the "called scope" (see late static bindings).

The rule is that a call with :: is an instance call if and only if:

  • the target method is not declared as static and
  • there is a compatible object context at the time of the call, meaning these must be true:
    1. the call is made from a context where $this exists and
    2. the class of $this is either the class of the method being called or a subclass of it.

Example:

class A {
    public function func_instance() {
        echo "in ", __METHOD__, "\n";
    }
    public function callDynamic() {
        echo "in ", __METHOD__, "\n";
        B::dyn();
    }

}

class B extends A {
    public static $prop_static = 'B::$prop_static value';
    public $prop_instance = 'B::$prop_instance value';

    public function func_instance() {
        echo "in ", __METHOD__, "\n";
        /* this is one exception where :: is required to access an
         * instance member.
         * The super implementation of func_instance is being
         * accessed here */
        parent::func_instance();
        A::func_instance(); //same as the statement above
    }

    public static function func_static() {
        echo "in ", __METHOD__, "\n";
    }

    public function __call($name, $arguments) {
        echo "in dynamic $name (__call)", "\n";
    }

    public static function __callStatic($name, $arguments) {
        echo "in dynamic $name (__callStatic)", "\n";
    }

}

echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";

echo '$b->func_instance():', "\n", $b->func_instance(), "\n";

/* This is more tricky
 * in the first case, a static call is made because $this is an
 * instance of A, so B::dyn() is a method of an incompatible class
 */
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
 * instance of B (despite the fact we are in a method of A), so
 * B::dyn() is a method of a compatible class (namely, it's the
 * same class as the object's)
 */
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";

Output:

B::$prop_static: B::$prop_static value
B::func_static(): in B::func_static

$b->prop_instance: B::$prop_instance value
$b->func_static(): in B::func_static

$b->func_instance():
in B::func_instance
in A::func_instance
in A::func_instance

$a->dyn():
in A::callDynamic
in dynamic dyn (__callStatic)

$b->dyn():
in A::callDynamic
in dynamic dyn (__call)

How to convert OutputStream to InputStream?

There seem to be many links and other such stuff, but no actual code using pipes. The advantage of using java.io.PipedInputStream and java.io.PipedOutputStream is that there is no additional consumption of memory. ByteArrayOutputStream.toByteArray() returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of it. Then writing to an InputStream means you now have three copies of the data.

The code:

// take the copy of the stream and re-write it to an InputStream
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(new Runnable() {
    public void run () {
        try {
            // write the original OutputStream to the PipedOutputStream
            // note that in order for the below method to work, you need
            // to ensure that the data has finished writing to the
            // ByteArrayOutputStream
            originalByteArrayOutputStream.writeTo(out);
        }
        catch (IOException e) {
            // logging and exception handling should go here
        }
        finally {
            // close the PipedOutputStream here because we're done writing data
            // once this thread has completed its run
            if (out != null) {
                // close the PipedOutputStream cleanly
                out.close();
            }
        }   
    }
}).start();

This code assumes that the originalByteArrayOutputStream is a ByteArrayOutputStream as it is usually the only usable output stream, unless you're writing to a file. I hope this helps! The great thing about this is that since it's in a separate thread, it also is working in parallel, so whatever is consuming your input stream will be streaming out of your old output stream too. That is beneficial because the buffer can remain smaller and you'll have less latency and less memory usage.

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I solved it by putting this:

@Override
protected void onDestroy() {
    accessTokenTracker.stopTracking();
    super.onDestroy();
}

Android Studio : unmappable character for encoding UTF-8

A few encoding issues that I had to face couldn't be solved by above solutions. I had to either update my Android Studio or run test cases using following command in the AS terminal.

gradlew clean assembleDebug testDebug

P.S your encoding settings for IDE and project should match.

Hope it helps !

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

  1. Clean project
  2. Rebuild project
  3. Sync Gradle

it work for me

How to find the Center Coordinate of Rectangle?

The center of rectangle is the midpoint of the diagonal end points of rectangle.

Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 ).

That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2

Let me know your code.

How to loop through elements of forms with JavaScript?

You need to get a reference of your form, and after that you can iterate the elements collection. So, assuming for instance:

<form method="POST" action="submit.php" id="my-form">
  ..etc..
</form>

You will have something like:

var elements = document.getElementById("my-form").elements;

for (var i = 0, element; element = elements[i++];) {
    if (element.type === "text" && element.value === "")
        console.log("it's an empty textfield")
}

Notice that in browser that would support querySelectorAll you can also do something like:

var elements = document.querySelectorAll("#my-form input[type=text][value='']")

And you will have in elements just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:

var elements = document.querySelectorAll("#my-form input[type=text]")

for (var i = 0, element; element = elements[i++];) {
    if (element.value === "")
        console.log("it's an empty textfield")
}

You will basically save one check.

How to load all modules in a folder?

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)

Javascript Audio Play on click

Now that the Web Audio API is here and gaining browser support, that could be a more robust option.

Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

"Object doesn't support property or method 'find'" in IE

You are using the JavaScript array.find() method. Note that this is standard JS, and has nothing to do with jQuery. In fact, your entire code in the question makes no use of jQuery at all.

You can find the documentation for array.find() here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

If you scroll to the bottom of this page, you will note that it has browser support info, and you will see that it states that IE does not support this method.

Ironically, your best way around this would be to use jQuery, which does have similar functionality that is supported in all browsers.

How do I fix a NoSuchMethodError?

I've encountered this error too.

My problem was that I've changed a method's signature, something like

void invest(Currency money){...}

into

void invest(Euro money){...}

This method was invoked from a context similar to

public static void main(String args[]) {
    Bank myBank = new Bank();

    Euro capital = new Euro();
    myBank.invest(capital);
}

The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.

The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.

This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.

My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.

The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.

The original disassembled bytecode (generated with the javap tool) looks like this:

 #7 = Methodref          #2.#22         // Bank.invest:(LCurrency;)V

After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.

Hope this helps.

Why does Java have transient fields?

Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

What is serialization?

Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. For that purpose, every class or interface must implement the Serializable interface. It is a marker interface without any methods.

Now what is the transient keyword and its purpose?

By default, all of object's variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted. That is the main purpose of the transient keyword.

I want to explain the above two points with the following example:

package javabeat.samples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class NameStore implements Serializable{
    private String firstName;
    private transient String middleName;
    private String lastName;

    public NameStore (String fName, String mName, String lName){
        this.firstName = fName;
        this.middleName = mName;
        this.lastName = lName;
    }

    public String toString(){
        StringBuffer sb = new StringBuffer(40);
        sb.append("First Name : ");
        sb.append(this.firstName);
        sb.append("Middle Name : ");
        sb.append(this.middleName);
        sb.append("Last Name : ");
        sb.append(this.lastName);
        return sb.toString();
    }
}

public class TransientExample{
    public static void main(String args[]) throws Exception {
        NameStore nameStore = new NameStore("Steve", "Middle","Jobs");
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("nameStore"));
        // writing to object
        o.writeObject(nameStore);
        o.close();

        // reading from object
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("nameStore"));
        NameStore nameStore1 = (NameStore)in.readObject();
        System.out.println(nameStore1);
    }
}

And the output will be the following:

First Name : Steve
Middle Name : null
Last Name : Jobs

Middle Name is declared as transient, so it will not be stored in the persistent storage.

Source

Should I use scipy.pi, numpy.pi, or math.pi?

One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:

import math
import numpy
import scipy
import sympy

print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

Absolute vs relative URLs

A URL that starts with the URL scheme and scheme specific part (http://, https://, ftp://, etc.) is an absolute URL.

Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.

Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.

App can't be opened because it is from an unidentified developer

I had got the same error. Because of security reasons, I could not see option for allowing Apps downloaded from Anywhere in System preference-> Security Tab.

I removed the extended attribute from Zip file by below command.

xattr -d com.apple.quarantine [Zip file path] 

And then got below error:- org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: javax/annotation/PostConstruct

Resolved it by uninstalling all different versions of java and installed just 1.8.0_231.

Worked finally.

Skip certain tables with mysqldump

for multiple databases:

mysqldump -u user -p --ignore-table=db1.tbl1 --ignore-table=db2.tbl1 --databases db1 db2 ..

Read line by line in bash script

FILE=test

while read CMD; do
    echo "$CMD"
done < "$FILE"

A redirection with < "$FILE" has a few advantages over cat "$FILE" | while .... It avoids a useless use of cat, saving an unnecessary child process. It also avoids a common pitfall where the loop runs in a subshell. In bash, commands in a | pipeline run in subshells, which means variable assignments are lost after the loop ends. Redirection with < doesn't have that problem, so you could use $CMD after the loop or modify other variables inside the loop. It also, again, avoids unnecessary child processes.

There are some additional improvements that could be made:

  • Add IFS= so that read won't trim leading and trailing whitespace from each line.
  • Add -r to read to prevent from backslashes from being interpreted as escape sequences.
  • Lower case CMD and FILE. The bash convention is only environmental and internal shell variables are uppercase.
  • Use printf in place of echo which is safer if $cmd is a string like -n, which echo would interpret as a flag.
file=test

while IFS= read -r cmd; do
    printf '%s\n' "$cmd"
done < "$file"

How to use *ngIf else?

<div *ngIf="this.model.SerialNumber != '';then ConnectedContent else DisconnectedContent" class="data-font">    </div>

<ng-template #ConnectedContent class="data-font">Connected</ng-template>
<ng-template #DisconnectedContent class="data-font">Disconnected</ng-template>

One command to create a directory and file inside it linux command

Just a simple command below is enough.

mkdir a && touch !$/file.txt

Thx

SQL permissions for roles

Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:

GRANT ALL ON table1 TO doctor 

Users in that role will have no permissions whatsoever to other tables (not even read).