Programs & Examples On #Caucho

Caucho is an information technology company that produces web server software and application server software as well as the originators of Quercus and Hessian open source projects.

Autowiring fails: Not an managed Type

you need check packagesToScan.

<bean id="entityManagerFactoryDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    <property name="dataSource" ref="dataSourceDB" />
    <property name="persistenceUnitName" value="persistenceUnitDB" />
    <property name="packagesToScan" value="at.naviclean.domain" />
                                            //here
 .....

Wait for a process to finish

There's no builtin. Use kill -0 in a loop for a workable solution:

anywait(){

    for pid in "$@"; do
        while kill -0 "$pid"; do
            sleep 0.5
        done
    done
}

Or as a simpler oneliner for easy one time usage:

while kill -0 PIDS 2> /dev/null; do sleep 1; done;

As noted by several commentators, if you want to wait for processes that you do not have the privilege to send signals to, you have find some other way to detect if the process is running to replace the kill -0 $pid call. On Linux, test -d "/proc/$pid" works, on other systems you might have to use pgrep (if available) or something like ps | grep "^$pid ".

How to recursively download a folder via FTP on Linux

toggle the prompt by PROMPT command.

Usage:

ftp>cd /to/directory    
ftp>prompt    
ftp>mget  *

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Volley JsonObjectRequest Post request not working

try to use this helper class

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

Determining Referer in PHP

What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "http://example.com/index.php?token={$token}";

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])
{
    show_404();
} 

//Continue with the rest of code

I do know of secure sites that do the equivalent of this for all their secure pages.

Access non-numeric Object properties by index?

You can use the Object.values() method if you dont want to use the Object.keys().

As opposed to the Object.keys() method that returns an array of a given object's own enumerable properties, so for instance:

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.keys(object1));

Would print out the following array:

[ 'a', 'b', 'c' ]

The Object.values() method returns an array of a given object's own enumerable property values.

So if you have the same object but use values instead,

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.values(object1));

You would get the following array:

[ 'somestring', 42, false ]

So if you wanted to access the object1.b, but using an index instead you could use:

Object.values(object1)[1] === 42

You can read more about this method here.

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Why are you not able to declare a class as static in Java?

One can look at PlatformUI in Eclipse for a class with static methods and private constructor with itself being final.

public final class <class name>
{
   //static constants
   //static memebers
}

TypeError: $ is not a function WordPress

jQuery might be missing.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

Remove or uninstall library previously added : cocoapods

The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:

  1. Install clean:

    $ sudo gem install cocoapods-clean
    
  2. Run deintegrate in the folder of the project:

    $ pod deintegrate
    
  3. Clean (this tool is no longer available):

    $ pod clean
    
  4. Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:

    $ pod install
    

Done.

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

How to pass a list from Python, by Jinja2 to JavaScript

Make some invisible HTML tags like <label>, <p>, <input> etc. and name its id, and the class name is a pattern so that you can retrieve it later.

Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.

_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_

Now you can retrieve the data in javascript using some javascript operation like below -

_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
 _x000D_
for (var i = 0; i < total_len; i++) {_x000D_
    var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
    var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
    _x000D_
    //Do what you need to do with tm1 and tm2._x000D_
    _x000D_
    console.log(tm1);_x000D_
    console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to iterate over a std::map full of strings in C++

Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.

Reactjs convert html string to jsx

You can also use Parser() from html-react-parser. I have used the same. Link shared.

Finding the mode of a list

def mode(data):
    lst =[]
    hgh=0
    for i in range(len(data)):
        lst.append(data.count(data[i]))
    m= max(lst)
    ml = [x for x in data if data.count(x)==m ] #to find most frequent values
    mode = []
    for x in ml: #to remove duplicates of mode
        if x not in mode:
        mode.append(x)
    return mode
print mode([1,2,2,2,2,7,7,5,5,5,5])

Opacity of div's background without affecting contained element in IE 8?

Try setting the z-index higher on the contained element.

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

XPath: Get parent node from child node

This works in my case. I hope you can extract meaning out of it.

//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

I was getting this error today. In my case, looking at the ERRORLOG file on the SQL server gave me this error:

Login failed for user ''. Reason: Failed to open the database '' specified in the login properties.

This was because I had deleted the "Default database" of this user a few days ago. Setting the default database to my new database fixed the problem.

Hope this helps someone else.

How can I see which Git branches are tracking which remote / upstream branch?

Very much a porcelain command, not good if you want this for scripting:

git branch -vv   # doubly verbose!

Note that with git 1.8.3, that upstream branch is displayed in blue (see "What is this branch tracking (if anything) in git?")


If you want clean output, see arcresu's answer - it uses a porcelain command that I don't believe existed at the time I originally wrote this answer, so it's a bit more concise and works with branches configured for rebase, not just merge.

How to programmatically tell if a Bluetooth device is connected?

I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:

BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;

for (BluetoothDevice device : devices) {
  status = bm.getConnectionState(device, BLuetoothGatt.GATT);
  // compare status to:
  //   BluetoothProfile.STATE_CONNECTED
  //   BluetoothProfile.STATE_CONNECTING
  //   BluetoothProfile.STATE_DISCONNECTED
  //   BluetoothProfile.STATE_DISCONNECTING
}

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

Suppress warning messages using mysql from within Terminal, but password written in bash script

If you wish to use a password in the command line, I've found that this works for filtering out the specific error message:

mysqlcommand 2>&1 | grep -v "Warning: Using a password"

It's basically redirecting standard error to standard output -- and using grep to drop all lines that match "Warning: Using a password".

This way, you can see any other output, including errors. I use this for various shell scripts, etc.

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

How do I make a "div" button submit the form its sitting in?

Are you aware of <button> elements? <button> elements can be styled just like <div> elements and can have type="submit" so they submit the form without javascript:

<form action="whatever.html" method="post">  
    <button name="mysubmitbutton" id="mysubmitbutton" type="submit" class="customButton">  
    Button Text
    </button>  
</form>  

Using a <button> is also more semantic, whereas <div> is very generic. You get the following benefits for free:

  • JavaScript is not necessary to submit the form
  • Accessibility tools, e.g. screen readers, will (correctly) treat it as a button and not part of the normal text flow
  • <button type="submit"> becomes a "default" button, which means the return key will automatically submit the form. You can't do this with a <div>, you'd have to add a separate keydown handler to the <form> element.

There's one (non-) caveat: a <button> can only have phrasing content, though it's unlikely anyone would need any other type of content when using the element to submit a form.

Countdown timer in React

The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:

...
startTimer = () => {
  let interval = setInterval(this.timer.bind(this), 1000);
  this.setState({ interval });
};

As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).

Another option is to use another arrow function:

startTimer = () => {
  let interval = setInterval(() => this.timer(), 1000);
  this.setState({ interval });
};

Rounding integer division (instead of truncating)

(Edited) Rounding integers with floating point is the easiest solution to this problem; however, depending on the problem set is may be possible. For example, in embedded systems the floating point solution may be too costly.

Doing this using integer math turns out to be kind of hard and a little unintuitive. The first posted solution worked okay for the the problem I had used it for but after characterizing the results over the range of integers it turned out to be very bad in general. Looking through several books on bit twiddling and embedded math return few results. A couple of notes. First, I only tested for positive integers, my work does not involve negative numerators or denominators. Second, and exhaustive test of 32 bit integers is computational prohibitive so I started with 8 bit integers and then mades sure that I got similar results with 16 bit integers.

I started with the 2 solutions that I had previously proposed:

#define DIVIDE_WITH_ROUND(N, D) (((N) == 0) ? 0:(((N * 10)/D) + 5)/10)

#define DIVIDE_WITH_ROUND(N, D) (N == 0) ? 0:(N - D/2)/D + 1;

My thought was that the first version would overflow with big numbers and the second underflow with small numbers. I did not take 2 things into consideration. 1.) the 2nd problem is actually recursive since to get the correct answer you have to properly round D/2. 2.) In the first case you often overflow and then underflow, the two canceling each other out. Here is an error plot of the two (incorrect) algorithms:Divide with Round1 8 bit x=numerator y=denominator

This plot shows that the first algorithm is only incorrect for small denominators (0 < d < 10). Unexpectedly it actually handles large numerators better than the 2nd version.

Here is a plot of the 2nd algorithm: 8 bit signed numbers 2nd algorithm.

As expected it fails for small numerators but also fails for more large numerators than the 1st version.

Clearly this is the better starting point for a correct version:

#define DIVIDE_WITH_ROUND(N, D) (((N) == 0) ? 0:(((N * 10)/D) + 5)/10)

If your denominators is > 10 then this will work correctly.

A special case is needed for D == 1, simply return N. A special case is needed for D== 2, = N/2 + (N & 1) // Round up if odd.

D >= 3 also has problems once N gets big enough. It turns out that larger denominators only have problems with larger numerators. For 8 bit signed number the problem points are

if (D == 3) && (N > 75))
else if ((D == 4) && (N > 100))
else if ((D == 5) && (N > 125))
else if ((D == 6) && (N > 150))
else if ((D == 7) && (N > 175))
else if ((D == 8) && (N > 200))
else if ((D == 9) && (N > 225))
else if ((D == 10) && (N > 250))

(return D/N for these)

So in general the the pointe where a particular numerator gets bad is somewhere around
N > (MAX_INT - 5) * D/10

This is not exact but close. When working with 16 bit or bigger numbers the error < 1% if you just do a C divide (truncation) for these cases.

For 16 bit signed numbers the tests would be

if ((D == 3) && (N >= 9829))
else if ((D == 4) && (N >= 13106))
else if ((D == 5) && (N >= 16382))
else if ((D == 6) && (N >= 19658))
else if ((D == 7) && (N >= 22935))
else if ((D == 8) && (N >= 26211))
else if ((D == 9) && (N >= 29487))
else if ((D == 10) && (N >= 32763))

Of course for unsigned integers MAX_INT would be replaced with MAX_UINT. I am sure there is an exact formula for determining the largest N that will work for a particular D and number of bits but I don't have any more time to work on this problem...

(I seem to be missing this graph at the moment, I will edit and add later.) This is a graph of the 8 bit version with the special cases noted above:![8 bit signed with special cases for 0 < N <= 10 3

Note that for 8 bit the error is 10% or less for all errors in the graph, 16 bit is < 0.1%.

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

What's the fastest way to loop through an array in JavaScript?

As of September 2017 these jsperf tests are showing the following pattern to be most performant on Chrome 60:

function foo(x) {
 x;
};
arr.forEach(foo);

Is anyone able to reproduce?

Access Google's Traffic Data through a Web Service

There is no way (or at least no reasonably easy and convenient way) to get the raw traffic data from Google Maps Javascript API v3. Even if you could do it, doing so is likely to violate some clause in the Terms Of Service for Google Maps. You would have to get this information from another service. I doubt there is a free service that provides this information at the current time, but I would love it if someone proved me wrong on that.

As @crdzoba points out, Bing Maps API exposes some traffic data. Perhaps that can fill your needs. It's not clear from the documentation how much traffic data that exposes as it's only data about "incidents". Slow traffic due to construction would be in there, but it's not obvious to me whether slow traffic due simply to volume would be.

UPDATE (March 2016): A lot has happened since this answer was written in 2011, but the core points appear to hold up: You won't find raw traffic data in free API services (at least not for the U.S., and probably not most other places). But if you don't mind paying a bit and/or if you just need things like "travel time for a specific route taking traffic into consideration" you have options. @Anto's answer, for example, points to Google's Maps For Work as a paid API service that allows you to get travel times taking traffic into consideration.

In what cases do I use malloc and/or new?

new vs malloc()

1) new is an operator, while malloc() is a function.

2) new calls constructors, while malloc() does not.

3) new returns exact data type, while malloc() returns void *.

4) new never returns a NULL (will throw on failure) while malloc() returns NULL

5) Reallocation of memory not handled by new while malloc() can

CSS3 background image transition

You can use pseudo element to get the effect you want like I did in that Fiddle.

CSS:

.title a {
    display: block;
    width: 340px;
    height: 338px;
    color: black;
    position: relative;
}
.title a:after {
    background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
    content: "";
    opacity: 0;
    width: inherit;
    height: inherit;
    position: absolute;
    top: 0;
    left: 0;
    /* TRANSISITION */
    transition: opacity 1s ease-in-out;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{   
    opacity: 1;
}

HTML:

<div class="title">
    <a href="#">HYPERLINK</a>
</div>

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Where to find Java JDK Source Code?

Chances that you already got the source code with the JDK, it is matter of finding where it is. In case, JDK folder doesn't contain the source code:

sudo apt-get install openjdk-7-source

OSX Folks, search in homebrew formulas.

In ubuntu, the command above would put your souce file under: /usr/lib/jvm/openjdk-7/

Good news is that Eclipse will take you there already (How to bind Eclipse to the Java source code):

Follow the orange buttons

enter image description here enter image description here enter image description here

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

For OSX it's even easier. Your machine should come with a version of Apache already installed. All you need to do is locate the php lib for that version (which is likely 5.2.x) and swap it out.

This is the command you'd run from terminal*

cp /usr/libexec/apache2/libphp5.so /Applications/XAMPP/xamppfiles/modules/libphp5.so

I tested this on 10.5 (Leopard), so ymmv. * all the caveats about this might break your system, make a backup, blah blah blah.

Edit: On 10.4 (Tiger), Xampp 1.73, using the libphp5.so-files found at Mamp, this does not work at all.

Using custom fonts using CSS?

If you dont find any fonts that you like from Google.com/webfonts or fontsquirrel.com you can always make your own web font with a font you made.

here's a nice tutorial: Make your own font face web font kit

Although im not sure about preventing someone from downloading your font.

Hope this helps,

Adjust UILabel height depending on the text

This method will give perfect height

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;


title_size = [text boundingRectWithSize:constraint
                                options:NSStringDrawingUsesLineFragmentOrigin
                             attributes:@{ NSFontAttributeName : font }
                                context:nil].size;

totalHeight = ceil(title_size.height);

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}

How do you clear the SQL Server transaction log?

To Truncate the log file:

  • Backup the database
  • Detach the database, either by using Enterprise Manager or by executing : Sp_DetachDB [DBName]
  • Delete the transaction log file. (or rename the file, just in case)
  • Re-attach the database again using: Sp_AttachDB [DBName]
  • When the database is attached, a new transaction log file is created.

To Shrink the log file:

  • Backup log [DBName] with No_Log
  • Shrink the database by either:

    Using Enterprise manager :- Right click on the database, All tasks, Shrink database, Files, Select log file, OK.

    Using T-SQL :- Dbcc Shrinkfile ([Log_Logical_Name])

You can find the logical name of the log file by running sp_helpdb or by looking in the properties of the database in Enterprise Manager.

Sort JavaScript object by key

Not sure if this answers the question, but this is what I needed.

Maps.iterate.sorted = function (o, callback) {
    var keys = Object.keys(o), sorted = keys.sort(), k; 
    if ( callback ) {
            var i = -1;
            while( ++i < sorted.length ) {
                    callback(k = sorted[i], o[k] );
            }
    }

    return sorted;
}

Called as :

Maps.iterate.sorted({c:1, b:2, a:100}, function(k, v) { ... } ) 

JSON to TypeScript class instance?

Why could you not just do something like this?

class Foo {
  constructor(myObj){
     Object.assign(this, myObj);
  }
  get name() { return this._name; }
  set name(v) { this._name = v; }
}

let foo = new Foo({ name: "bat" });
foo.toJSON() //=> your json ...

Finding the 'type' of an input element

Check the type property. Would that suffice?

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

Input widths on Bootstrap 3

I'm also struggled with the same problem, and this is my solution.

HTML source

<div class="input_width">
    <input type="text" class="form-control input-lg" placeholder="sample">
</div>

Cover input code with another div class

CSS source

.input_width{
   width: 450px;
}

give any width or margin setting on covered div class.

Bootstrap's input width is always default as 100%, so width is follow that covered width.

This is not the best way, but easiest and only solution that I solved the problem.

Hope this helped.

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

Lumen: get URL parameter in a Blade view

if you use route and pass paramater use this code in your blade file

{{dd(request()->route()->parameters)}}

Convert an array to string

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

Initializing a list to a known number of elements in Python

@Steve already gave a good answer to your question:

verts = [None] * 1000

Warning: As @Joachim Wuttke pointed out, the list must be initialized with an immutable element. [[]] * 1000 does not work as expected because you will get a list of 1000 identical lists (similar to a list of 1000 points to the same list in C). Immutable objects like int, str or tuple will do fine.

Alternatives

Resizing lists is slow. The following results are not very surprising:

>>> N = 10**6

>>> %timeit a = [None] * N
100 loops, best of 3: 7.41 ms per loop

>>> %timeit a = [None for x in xrange(N)]
10 loops, best of 3: 30 ms per loop

>>> %timeit a = [None for x in range(N)]
10 loops, best of 3: 67.7 ms per loop

>>> a = []
>>> %timeit for x in xrange(N): a.append(None)
10 loops, best of 3: 85.6 ms per loop

But resizing is not very slow if you don't have very large lists. Instead of initializing the list with a single element (e.g. None) and a fixed length to avoid list resizing, you should consider using list comprehensions and directly fill the list with correct values. For example:

>>> %timeit a = [x**2 for x in xrange(N)]
10 loops, best of 3: 109 ms per loop

>>> def fill_list1():
    """Not too bad, but complicated code"""
    a = [None] * N
    for x in xrange(N):
        a[x] = x**2
>>> %timeit fill_list1()
10 loops, best of 3: 126 ms per loop

>>> def fill_list2():
    """This is slow, use only for small lists"""
    a = []
    for x in xrange(N):
        a.append(x**2)
>>> %timeit fill_list2()
10 loops, best of 3: 177 ms per loop

Comparison to numpy

For huge data set numpy or other optimized libraries are much faster:

from numpy import ndarray, zeros
%timeit empty((N,))
1000000 loops, best of 3: 788 ns per loop

%timeit zeros((N,))
100 loops, best of 3: 3.56 ms per loop

Compare dates with javascript

you can done this way also.

if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
        console.log("done");
}

OR

if (dateFormat(first, "mm-dd-yyyy") >  dateFormat(second, "mm-dd-yyyy")) {
        console.log("done");
}

i use following plugin for dateFormat()

        var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;
            };

        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;

            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;
            }

            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");

            mask = String(dF.masks[mask] || mask || dF.masks["default"]);

            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;
            }

            var _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                };

            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
    }();

    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };

    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        ],
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        ]
    };

    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);
    };

How to use cURL to send Cookies?

You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use

curl -c /path/to/cookiefile http://yourhost/

to write to a cookie file and start engine and to use cookie you can use

curl -b /path/to/cookiefile  http://yourhost/

to read cookies from and start the cookie engine, or if it isn't a file it will pass on the given string.

Unit testing with mockito for constructors

Here is the code to mock this functionality using PowerMockito API.

Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);

You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
    // your testing code
}

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

Hot to get all form elements values using jQuery?

I needed to get the form data as some sort of object. I used this:

$('#preview_form').serializeArray().reduce((function(acc, val) {
  acc[val.name.replace('[', '_').replace(']', '')] = val.value;
  return acc;
}), {});

Question mark and colon in JavaScript

It is called the Conditional Operator (which is a ternary operator).

It has the form of: condition ? value-if-true : value-if-false
Think of the ? as "then" and : as "else".

Your code is equivalent to

if (max != 0)
  hsb.s = 255 * delta / max;
else
  hsb.s = 0;

How to squash commits in git after they have been pushed?

Minor difference to accepted answer, but I was having a lot of difficulty squashing and finally got it.

$ git rebase -i HEAD~4
  • At the interactive screen that opens up, replace pick with squash at the top for all the commits that you want to squash.
  • Save and close the editor through esc --> :wq

Push to the remote using:

$ git push origin branch-name --force

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

How to test that a registered variable is not empty?

when: myvar | default('', true) | trim != ''

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

Regex to split a CSV

Aaaand another answer here. :) Since I couldn't make the others quite work.

My solution both handles escaped quotes (double occurrences), and it does not include delimiters in the match.

Note that I have been matching against ' instead of " as that was my scenario, but simply replace them in the pattern for the same effect.

Here goes (remember to use the "ignore whitespace" flag /x if you use the commented version below) :

# Only include if previous char was start of string or delimiter
(?<=^|,)
(?:
  # 1st option: empty quoted string (,'',)
  '{2}
  |
  # 2nd option: nothing (,,)
  (?:)
  |
  # 3rd option: all but quoted strings (,123,)
  # (included linebreaks to allow multiline matching)
  [^,'\r\n]+
  |
  # 4th option: quoted strings (,'123''321',)
  # start pling
  ' 
    (?:
      # double quote
      '{2}
      |
      # or anything but quotes
      [^']+
    # at least one occurance - greedy
    )+
  # end pling
  '
)
# Only include if next char is delimiter or end of string
(?=,|$)

Single line version:

(?<=^|,)(?:'{2}|(?:)|[^,'\r\n]+|'(?:'{2}|[^']+)+')(?=,|$)

Regular expression visualization (if it works, debux has issues right now it seems - else follow the next link)

Debuggex Demo

regex101 example

How to send an object from one Android Activity to another using Intents?

We can send data one Activty1 to Activity2 with multiple ways like.
1- Intent
2- bundle
3- create an object and send through intent
.................................................
1 - Using intent
Pass the data through intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
intentActivity1.putExtra("name", "Android");
startActivity(intentActivity1);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
     String userName = getIntent().getStringExtra("name");
}
..................................................
2- Using Bundle
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putExtra("name", "Android");
intentActivity1.putExtra(bundle);
startActivity(bundle);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
     String userName = getIntent().getStringExtra("name");
}
..................................................
3-  Put your Object into Intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
            intentActivity1.putExtra("myobject", myObject);
            startActivity(intentActivity1); 
 Receive object in the Activity2 Class
Intent intent = getIntent();
    Myobject obj  = (Myobject) intent.getSerializableExtra("myobject");

Retrieve the position (X,Y) of an HTML element relative to the browser window

You might be better served by using a JavaScript framework, that has functions to return such information (and so much more!) in a browser-independant fashion. Here are a few:

With these frameworks, you could do something like: $('id-of-img').top to get the y-pixel coordinate of the image.

Fastest JavaScript summation

You should be able to use reduce.

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);

Source

And with arrow functions introduced in ES6, it's even simpler:

sum = array.reduce((pv, cv) => pv + cv, 0);

Make: how to continue after a command fails?

Change clean to

rm -f .lambda .lambda_t .activity .activity_t_lambda

I.e. don't prompt for remove; don't complain if file doesn't exist.

Open multiple Eclipse workspaces on the Mac

Based on a previous answer that helped me, but different directory:

cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &

Thanks

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

The question is already answered, Updating answer to add the PyCharm bin directory to $PATH var, so that pycharm editor can be opened from anywhere(path) in terminal.

Edit the bashrc file,

nano .bashrc

Add following line at the end of bashrc file

export PATH="<path-to-unpacked-pycharm-installation-directory>/bin:$PATH"

Now you can open pycharm from anywhere in terminal

pycharm.sh

Session TimeOut in web.xml

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Try this. It's helped me to change from ConstraintLayout to RelativeLayout.

Try this... That helped me to change from ConstraintLayout to RelativeLayout

How to always show the vertical scrollbar in a browser?

jQuery shouldn't be required. You could try adding the CSS:

body    {overflow-y:scroll;}

This works across the latest browsers, even IE6.

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

PHP convert XML to JSON

Best solution which works like a charm

$fileContents= file_get_contents($url);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

$fileContents = trim(str_replace('"', "'", $fileContents));

$simpleXml = simplexml_load_string($fileContents);

//$json = json_encode($simpleXml); // Remove // if you want to store the result in $json variable

echo '<pre>'.json_encode($simpleXml,JSON_PRETTY_PRINT).'</pre>';

Source

MVC 5 Access Claims Identity User Data

var claim = User.Claims.FirstOrDefault(c => c.Type == "claim type here");

Correctly Parsing JSON in Swift 3

{
    "User":[
      {
        "FirstUser":{
        "name":"John"
        },
       "Information":"XY",
        "SecondUser":{
        "name":"Tom"
      }
     }
   ]
}

If I create model using previous json Using this link [blog]: http://www.jsoncafe.com to generate Codable structure or Any Format

Model

import Foundation
struct RootClass : Codable {
    let user : [Users]?
    enum CodingKeys: String, CodingKey {
        case user = "User"
    }

    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        user = try? values?.decodeIfPresent([Users].self, forKey: .user)
    }
}

struct Users : Codable {
    let firstUser : FirstUser?
    let information : String?
    let secondUser : SecondUser?
    enum CodingKeys: String, CodingKey {
        case firstUser = "FirstUser"
        case information = "Information"
        case secondUser = "SecondUser"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        firstUser = try? FirstUser(from: decoder)
        information = try? values?.decodeIfPresent(String.self, forKey: .information)
        secondUser = try? SecondUser(from: decoder)
    }
}
struct SecondUser : Codable {
    let name : String?
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        name = try? values?.decodeIfPresent(String.self, forKey: .name)
    }
}
struct FirstUser : Codable {
    let name : String?
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        name = try? values?.decodeIfPresent(String.self, forKey: .name)
    }
}

Parse

    do {
        let res = try JSONDecoder().decode(RootClass.self, from: data)
        print(res?.user?.first?.firstUser?.name ?? "Yours optional value")
    } catch {
        print(error)
    }

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

Install windows service without InstallUtil.exe

Not double click, you run it with the correct command line parameters, so type something like MyService -i and then MyService -u to uninstall it`.

You could otherwise use sc.exe to install and uninstall it (or copy along InstallUtil.exe).

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

How to get IP address of the device from code?

Compiling some of the ideas to get the wifi ip from the WifiManager in a nicer kotlin solution:

private fun getWifiIp(context: Context): String? {
  return context.getSystemService<WifiManager>().let {
     when {
      it == null -> "No wifi available"
      !it.isWifiEnabled -> "Wifi is disabled"
      it.connectionInfo == null -> "Wifi not connected"
      else -> {
        val ip = it.connectionInfo.ipAddress
        ((ip and 0xFF).toString() + "." + (ip shr 8 and 0xFF) + "." + (ip shr 16 and 0xFF) + "." + (ip shr 24 and 0xFF))
      }
    }
  }
}

Alternatively you can get the ip adresses of ip4 loopback devices via the NetworkInterface:

fun getNetworkIp4LoopbackIps(): Map<String, String> = try {
  NetworkInterface.getNetworkInterfaces()
    .asSequence()
    .associate { it.displayName to it.ip4LoopbackIps() }
    .filterValues { it.isNotEmpty() }
} catch (ex: Exception) {
  emptyMap()
}

private fun NetworkInterface.ip4LoopbackIps() =
  inetAddresses.asSequence()
    .filter { !it.isLoopbackAddress && it is Inet4Address }
    .map { it.hostAddress }
    .filter { it.isNotEmpty() }
    .joinToString()

How to clear basic authentication details in chrome

This isn't exactly what the question is asking for but in case you accidentally saved basic auth credentials and want to clear them or update them:

https://support.google.com/accounts/answer/6197437

  1. Open Chrome.
  2. At the top right, click More > and then Settings.
  3. At the bottom, click Advanced.
  4. Under "Passwords and forms," click Manage passwords.
  5. Under "Saved Passwords", click Remove on the site you want to clear saved basic auth credentials.

Steps 1-4 can be quickly navigated with this link: chrome://settings/passwords

This worked in Chrome Version 59.0.3071.115

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

If you add the android:theme="@style/Theme.AppCompat.Light" to <application> in AndroidManifest.xml file, problem is solving.

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

RegEx to extract all matches from string using RegExp.exec

Here is my function to get the matches :

function getAllMatches(regex, text) {
    if (regex.constructor !== RegExp) {
        throw new Error('not RegExp');
    }

    var res = [];
    var match = null;

    if (regex.global) {
        while (match = regex.exec(text)) {
            res.push(match);
        }
    }
    else {
        if (match = regex.exec(text)) {
            res.push(match);
        }
    }

    return res;
}

// Example:

var regex = /abc|def|ghi/g;
var res = getAllMatches(regex, 'abcdefghi');

res.forEach(function (item) {
    console.log(item[0]);
});

Moving from one activity to another Activity in Android

It is mainly due to unregistered activity in manifest file as "NextActivity" Firstly register NextActivity in Manifest like

<activity android:name=".NextActivity">

then use the code in the where you want

Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);

where you have to call the NextActivity..

How to change MenuItem icon in ActionBar programmatically

You can't use findViewById() on menu items in onCreate() because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu() and then use it in your onClick().

private Menu menu;

In your onCreateOptionsMenu()

this.menu = menu;

In your button's onClick() method

menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));

Using sessions & session variables in a PHP Login Script

I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.

<?php
class Session
{
private $logged_in=false;
public $user_id;

function __construct() {
    session_start();
    $this->check_login();
if($this->logged_in) {
  // actions to take right away if user is logged in
} else {
  // actions to take right away if user is not logged in
}
}

public function is_logged_in() {
   return $this->logged_in;
}

public function login($user) {
// database should find user based on username/password
if($user){
  $this->user_id = $_SESSION['user_id'] = $user->id;
  $this->logged_in = true;
  }
}

public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}

private function check_login() {
if(isset($_SESSION['user_id'])) {
  $this->user_id = $_SESSION['user_id'];
  $this->logged_in = true;
} else {
  unset($this->user_id);
  $this->logged_in = false;
 }
}

}

$session = new Session();
?>

How permission can be checked at runtime without throwing SecurityException?

Check Permissions In KOTLIN (RunTime)

In Manifest: (android.permission.WRITE_EXTERNAL_STORAGE)

    fun checkPermissions(){

      var permission_array=arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
      if((ContextCompat.checkSelfPermission(this,permission_array[0]))==PackageManager.PERMI   SSION_DENIED){
        requestPermissions(permission_array,0)
      }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

          if(requestCode==0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

       //Do Your Operations Here

        ---------->
         //


          }
    }

How to check Grants Permissions at Run-Time?

original (not mine) post here

For special permissions, such as android.Manifest.permission.PACKAGE_USAGE_STATS used AppOpsManager:
Kotlin

private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
    var granted = false
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
        // requires kitkat
        val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

        // requires lollipop
        val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
                              android.os.Process.myUid(), applicationContext!!.packageName)

        if (mode == AppOpsManager.MODE_DEFAULT) {
            granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
        } else {
            granted = mode == AppOpsManager.MODE_ALLOWED
        }
    }

    return granted
}

and anywhere in code:

val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS

if (hasPermission(permission, permissionAppOpsManager)) {
    Timber.i("has permission: $permission")
    // do here what needs permission
} else {
    Timber.e("has no permission: $permission")
    // start activity to get permission
    startActivity(Intent(permissionActivity))
}

Other permissions you can get with TedPermission library

Hide all elements with class using plain Javascript

function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

var elements = new Array();
elements = getElementsByClassName('yourClassName');
for(i in elements ){
     elements[i].style.display = "none";
}

What does "#include <iostream>" do?

That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.

How to remove a field completely from a MongoDB document?

And for mongomapper,

  • Document: Shutoff
  • Field to remove: shutoff_type

Shutoff.collection.update( {}, { '$unset' => { 'shutoff_type': 1 } }, :multi => true )

Listing only directories using ls in Bash?

*/ is a pattern that matches all of the subdirectories in the current directory (* would match all files and subdirectories; the / restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use ls -d /home/alice/Documents/*/

wp-admin shows blank page, how to fix it?

My case was that I had generated code for three custom content types and then just pasted all the code in functions.php without renaming the "function custom_post_type" part of each function. After renaming like e.g "function employees", it worked like a charm....it displayed.

What's the difference between "static" and "static inline" function?

One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline functions from output by default, but will keep plain static functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline for static functions in headers.

How can I set size of a button?

GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.

A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)

Integer to IP Address - C

Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

void print_ip(unsigned int ip)
{
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;   
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
}

There is an implied bytes[0] = (ip >> 0) & 0xFF; at the first step.

Use snprintf() to print it to a string.

How can I turn a List of Lists into a List in Java 8?

You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:

List<List<Object>> list = ...
List<Object> flat = 
    list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

How to set locale in DatePipe in Angular 2?

Starting from Angular 9 localization process changed. Check out official doc.

Follow the steps below:

  1. Add localization package if it's not there yet: ng add @angular/localize
  2. As it's said in docs:

The Angular repository includes common locales. You can change your app's source locale for the build by setting the source locale in the sourceLocale field of your app's workspace configuration file (angular.json). The build process (described in Merge translations into the app in this guide) uses your app's angular.json file to automatically set the LOCALE_ID token and load the locale data.

so set locale in angular.json like this (list of available locales can be found here):

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "test-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "i18n": {
        "sourceLocale": "es"
      },
      ....
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          ...
          "configurations": {
            "production": {
             ...
            },
            "ru": {
              "localize": ["ru"]
            },
            "es": {
              "localize": ["es"]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "test-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "test-app:build:production"
            },
            "ru":{
              "browserTarget": "test-app:build:ru"
            },
            "es": {
              "browserTarget": "test-app:build:es"
            }
          }
        },
        ...
      }
    },
    ...
  "defaultProject": "test-app"
}

Basically you need to define sourceLocale in i18n section and add build configuration with specific locale like "localize": ["es"]. Optionally you can add it so serve section

  1. Build app with specific locale using build or serve: ng serve --configuration=es

How to avoid scientific notation for large numbers in JavaScript?

Your question:

number :0x68656c6c6f206f72656f
display:4.9299704811152646e+23

You can use this: https://github.com/MikeMcl/bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.

like this:

let ten =new BigNumber('0x68656c6c6f206f72656f',16);
console.log(ten.toString(10));
display:492997048111526447310191

How to make an input type=button act like a hyperlink and redirect using a get request?

For those who stumble upon this from a search (Google) and are trying to translate to .NET and MVC code. (as in my case)

@using (Html.BeginForm("RemoveLostRolls", "Process", FormMethod.Get)) {
     <input type="submit" value="Process" />
}

This will show a button labeled "Process" and take you to "/Process/RemoveLostRolls". Without "FormMethod.Get" it worked, but was seen as a "post".

Mark error in form using Bootstrap

(UPDATED with examples for Bootstrap v4, v3 and v3)

Examples of forms with validation classes for the past few major versions of Bootstrap.

Bootstrap v4

See the live version on codepen

bootstrap v4 form validation

<div class="container">
  <form>
    <div class="form-group row">
      <label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
      <div class="col-sm-7">
        <input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
      </div>
    </div>

    <div class="form-group row">
      <label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
      <div class="col-sm-7">
        <input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
      </div>
      <div class="col-sm-3">
        <small id="passwordHelp" class="text-danger">
          Must be 8-20 characters long.
        </small>      
      </div>
    </div>
  </form>
</div>

Bootstrap v3

See the live version on codepen

bootstrap v3 form validation

<form role="form">
  <div class="form-group has-warning">
    <label class="control-label" for="inputWarning">Input with warning</label>
    <input type="text" class="form-control" id="inputWarning">
    <span class="help-block">Something may have gone wrong</span>
  </div>
  <div class="form-group has-error">
    <label class="control-label" for="inputError">Input with error</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Please correct the error</span>
  </div>
  <div class="form-group has-info">
    <label class="control-label" for="inputError">Input with info</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Username is taken</span>
  </div>
  <div class="form-group has-success">
    <label class="control-label" for="inputSuccess">Input with success</label>
    <input type="text" class="form-control" id="inputSuccess" />
    <span class="help-block">Woohoo!</span>
  </div>
</form>

Bootstrap v2

See the live version on jsfiddle

bootstrap v2 form validation

The .error, .success, .warning and .info classes are appended to the .control-group. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)

  <form class="form-horizontal">
    <div class="control-group warning">
      <label class="control-label" for="inputWarning">Input with warning</label>
      <div class="controls">
        <input type="text" id="inputWarning">
        <span class="help-inline">Something may have gone wrong</span>
      </div>
    </div>
    <div class="control-group error">
      <label class="control-label" for="inputError">Input with error</label>
      <div class="controls">
        <input type="text" id="inputError">
        <span class="help-inline">Please correct the error</span>
      </div>
    </div>
    <div class="control-group info">
      <label class="control-label" for="inputInfo">Input with info</label>
      <div class="controls">
        <input type="text" id="inputInfo">
        <span class="help-inline">Username is taken</span>
      </div>
    </div>
    <div class="control-group success">
      <label class="control-label" for="inputSuccess">Input with success</label>
      <div class="controls">
        <input type="text" id="inputSuccess">
        <span class="help-inline">Woohoo!</span>
      </div>
    </div>
  </form>

What is the proper way to check if a string is empty in Perl?

For string comparisons in Perl, use eq or ne:

if ($str eq "")
{
  // ...
}

The == and != operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.

See the perlop man page for more information.

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

MVVM Passing EventArgs As Command Parameter

I try to keep my dependencies to a minimum, so I implemented this myself instead of going with EventToCommand of MVVMLight. Works for me so far, but feedback is welcome.

Xaml:

<i:Interaction.Behaviors>
    <beh:EventToCommandBehavior Command="{Binding DropCommand}" Event="Drop" PassArguments="True" />
</i:Interaction.Behaviors>

ViewModel:

public ActionCommand<DragEventArgs> DropCommand { get; private set; }

this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);

private void OnDrop(DragEventArgs e)
{
    // ...
}

EventToCommandBehavior:

/// <summary>
/// Behavior that will connect an UI event to a viewmodel Command,
/// allowing the event arguments to be passed as the CommandParameter.
/// </summary>
public class EventToCommandBehavior : Behavior<FrameworkElement>
{
    private Delegate _handler;
    private EventInfo _oldEvent;

    // Event
    public string Event { get { return (string)GetValue(EventProperty); } set { SetValue(EventProperty, value); } }
    public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(EventToCommandBehavior), new PropertyMetadata(null, OnEventChanged));

    // Command
    public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } }
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandBehavior), new PropertyMetadata(null));

    // PassArguments (default: false)
    public bool PassArguments { get { return (bool)GetValue(PassArgumentsProperty); } set { SetValue(PassArgumentsProperty, value); } }
    public static readonly DependencyProperty PassArgumentsProperty = DependencyProperty.Register("PassArguments", typeof(bool), typeof(EventToCommandBehavior), new PropertyMetadata(false));


    private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var beh = (EventToCommandBehavior)d;

        if (beh.AssociatedObject != null) // is not yet attached at initial load
            beh.AttachHandler((string)e.NewValue);
    }

    protected override void OnAttached()
    {
        AttachHandler(this.Event); // initial set
    }

    /// <summary>
    /// Attaches the handler to the event
    /// </summary>
    private void AttachHandler(string eventName)
    {
        // detach old event
        if (_oldEvent != null)
            _oldEvent.RemoveEventHandler(this.AssociatedObject, _handler);

        // attach new event
        if (!string.IsNullOrEmpty(eventName))
        {
            EventInfo ei = this.AssociatedObject.GetType().GetEvent(eventName);
            if (ei != null)
            {
                MethodInfo mi = this.GetType().GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
                _handler = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);
                ei.AddEventHandler(this.AssociatedObject, _handler);
                _oldEvent = ei; // store to detach in case the Event property changes
            }
            else
                throw new ArgumentException(string.Format("The event '{0}' was not found on type '{1}'", eventName, this.AssociatedObject.GetType().Name));
        }
    }

    /// <summary>
    /// Executes the Command
    /// </summary>
    private void ExecuteCommand(object sender, EventArgs e)
    {
        object parameter = this.PassArguments ? e : null;
        if (this.Command != null)
        {
            if (this.Command.CanExecute(parameter))
                this.Command.Execute(parameter);
        }
    }
}

ActionCommand:

public class ActionCommand<T> : ICommand
{
    public event EventHandler CanExecuteChanged;
    private Action<T> _action;

    public ActionCommand(Action<T> action)
    {
        _action = action;
    }

    public bool CanExecute(object parameter) { return true; }

    public void Execute(object parameter)
    {
        if (_action != null)
        {
            var castParameter = (T)Convert.ChangeType(parameter, typeof(T));
            _action(castParameter);
        }
    }
}

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

How to activate a specific worksheet in Excel?

I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"

for i=1 to thisworkbook.sheets.count
 sheets(i).activate
'You can add more code 
with activesheet
 'Code...
end with
next i

It will also, improve performance.

Trying to SSH into an Amazon Ec2 instance - permission error

.400 protects it by making it read only and only for the owner.
You can find the answer from the ASW guide.

chmod 400 yourPrivateKey.pem

enter image description here

True/False vs 0/1 in MySQL

If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.

The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):

CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

But, I always say that explaining the query like this:

EXPLAIN SELECT * FROM shirts WHERE size='medium';

will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.

How to use export with Python on Linux

Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.

$(python -c 'print "export MY_DATA=my_export"')

(you can also enclose the statement in backticks in some shells ``)

File input 'accept' attribute - is it useful?

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).

Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

SQL: How to get the id of values I just INSERTed?

Simplest answer:

command.ExecuteScalar()

by default returns the first column

Return Value Type: System.Object The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.

Copied from MSDN

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

What is the best way to filter a Java Collection?

Since the early release of Java 8, you could try something like:

Collection<T> collection = ...;
Stream<T> stream = collection.stream().filter(...);

For example, if you had a list of integers and you wanted to filter the numbers that are > 10 and then print out those numbers to the console, you could do something like:

List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);
numbers.stream().filter(n -> n > 10).forEach(System.out::println);

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

Here is a small hint that I hope might be useful to other poor saps that experienced the same issue as I did.

My Setup: Host: Windows 7 Enterprise - build 7601 SP 1 VM: VMware® Workstation 12 Player 12.1.1 build-3770994 (free) Guest: Fedora release 23

I naively failed to install open-vm-tools-desktop. I say naively because I had no idea such a thing existed, nor do I understand why instructions to install open-vm-tools do not (or at least where I read them, do not) include mentions of this package.

Installing open-vm-tools on its own appears to be nearly useless - the desktop package makes the copy and paste function - probably the single most important function of VMTools - work.

So, there you go. Install open-vm-tools-desktop, and copy-paste should work

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

iOS / Android cross platform development

There's also MoSync Mobile SDK

GPL and commercial licensing. There's a good overview of their approach here.

What is the opposite of evt.preventDefault();

This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.

$('.btnEdit').click(function(e) {

   var status = $(this).closest('tr').find('td').eq(3).html().trim();
   var tripId = $(this).attr('tripId');

  if (status == 'Completed') {

     e.preventDefault();
     alert("You can't edit completed reservations");

 } else if (tripId != '') {

    e.preventDefault();
    alert("You can't edit a reservation which is already attached to a trip");
 }
 //else it will continue as usual

});

Put text at bottom of div

<div id="container">
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
</div>

#container{
    width:450px;
    height:200px;
    margin:0px auto;
    border:1px solid red;
}

#container div{
    position:relative;
    width:100px;
    height:100px;
    border:1px solid #ccc;
    float:left;
    margin-right:5px;
}
#container div span{
    position:absolute;
    bottom:0;
    right:0;
}

Check working example at http://jsfiddle.net/7YTYu/2/

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md

The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).

As a quick fix in this particular situation you could just use the @transient annotation to tell it not to try to serialise the offending value (here, Spark.ctx is a custom class not Spark's one following OP's naming):

@transient
val rddList = Spark.ctx.parallelize(list)

You can also restructure code so that rddList lives somewhere else, but that is also nasty.

The Future is Probably Spores

In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.

http://docs.scala-lang.org/sips/pending/spores.html

A tip on Kryo serialization

When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:

"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."

Strategy for registering classes with kryo

Of course this only gives you type-level control not value-level control.

... more ideas to come.

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

The error means that you're navigating to a view whose model is declared as typeof Foo (by using @model Foo), but you actually passed it a model which is typeof Bar (note the term dictionary is used because a model is passed to the view via a ViewDataDictionary).

The error can be caused by

Passing the wrong model from a controller method to a view (or partial view)

Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view

var model = db.Foos.Select(x => new
{
    ID = x.ID,
    Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo

or passing a collection of objects to a view that expect a single object

var model = db.Foos.Where(x => x.ID == id);
return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo

The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using var.

Passing the wrong model from a view to a partial view

Given the following model

public class Foo
{
    public Bar MyBar { get; set; }
}

and a main view declared with @model Foo and a partial view declared with @model Bar, then

Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();
return View(model);

will return the correct model to the main view. However the exception will be thrown if the view includes

@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }

By default, the model passed to the partial view is the model declared in the main view and you need to use

@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }

to pass the instance of Bar to the partial view. Note also that if the value of MyBar is null (has not been initialized), then by default Foo will be passed to the partial, in which case, it needs to be

@Html.Partial("_Bar", new Bar())

Declaring a model in a layout

If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.

If you want to include the html for a separate model in a Layout, then in the Layout, use @Html.Action(...) to call a [ChildActionOnly] method initializes that model and returns a partial view for it.

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

PHP checkbox set to check based on database value

Add this code inside your input tag

<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

highlight the navigation menu for the current page

Css classes are here

<style type="text/css">
.mymenu
{
    background-color: blue;
    color: white;
}
.newmenu
{
    background-color: red;
    color: white;
}
</style>

Make your HTML like this, Set url as id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

Here write javascript, put this javascript after the HTML code.

    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();

Github Windows 'Failed to sync this branch'

One more thing that can cause this is when you map a network drive or connect a VHD after GitHub Desktop has already been started. The reason for this is that GitHub Desktop uses ssh-agent from the portable GIT install to establish connections, and never closes it... even if you uninstall the application. The process starts with no knowledge of the new drive and never refreshes itself, and when it is used to run the GIT commands to work on your repo it fails because it doesn't understand the paths.

The solution in this instance is to close GitHub Desktop and use Task Manager to terminate the running ssh-agent before starting it again. This will start a new instance of ssh-agent when needed which will pick up the new drive mappings, etc.

How do I list all files of a directory?

I prefer using the glob module, as it does pattern matching and expansion.

import glob
print(glob.glob("/home/adam/*.txt"))

It will return a list with the queried files:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

How to present UIAlertController when not in a view controller?

I tried everything mentioned, but with no success. The method which I used for Swift 3.0 :

extension UIAlertController {
    func show() {
        present(animated: true, completion: nil)
    }

    func present(animated: Bool, completion: (() -> Void)?) {
        if var topController = UIApplication.shared.keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            topController.present(self, animated: animated, completion: completion)
        }
    }
}

What is an efficient way to implement a singleton pattern in Java?

Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).

How to restore PostgreSQL dump file into Postgres databases?

By using pg_restore command you can restore postgres database

First open terminal type

sudo su postgres

Create new database

createdb [database name] -O [owner]

createdb test_db [-O openerp]

pg_restore -d [Database Name] [path of dump file]

pg_restore -d test_db /home/sagar/Download/sample_dbump

Wait for completion of database restoring.

Remember that dump file should have read, write, execute access, so for that you can apply chmod command

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I had a similar issue but I was unable to use the UserAgent class inside the fake_useragent module. I was running the code inside a docker container

import requests
import ujson
import random

response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]

I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.

How to set up java logging using a properties file? (java.util.logging)

Okay, first intuition is here:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL

The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....

In the mean time, try:

handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL

Update

No, duh, needed more coffee. Nevermind.

While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.


Another update

This line:

    FileInputStream configFile = new FileInputStream("/path/to/app.properties"));

has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.

Who is listening on a given TCP port on Mac OS X?

On Snow Leopard (OS X 10.6.8), running 'man lsof' yields:

lsof -i 4 -a

(actual manual entry is 'lsof -i 4 -a -p 1234')

The previous answers didn't work on Snow Leopard, but I was trying to use 'netstat -nlp' until I saw the use of 'lsof' in the answer by pts.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

It seems likely that this bucket was created in a different region, IE not us-west-2. That's the only time I've seen "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint."

US Standard is us-east-1

Difference between setUp() and setUpBeforeClass()

setUpBeforeClass is run before any method execution right after the constructor (run only once)

setUp is run before each method execution

tearDown is run after each method execution

tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)

How to get the PID of a process by giving the process name in Mac OS X ?

ps -o ppid=$(ps -ax | grep nameOfProcess | awk '{print $1}')

Prints out the changing process pid and then the parent PID. You can then kill the parent, or you can use that parentPID in the following command to get the name of the parent process:

ps -p parentPID -o comm=

For me the parent was 'login' :\

What HTTP traffic monitor would you recommend for Windows?

Fiddler is great when you are only interested in the http(s) side of the communications. It is also very useful when you are trying to inspect inside a https stream.

How to get a list of all files that changed between two Git commits?

The list of unstaged modified can be obtained using git status and the grep command like below. Something like git status -s | grep M:

root@user-ubuntu:~/project-repo-directory# git status -s | grep '^ M'
 M src/.../file1.js
 M src/.../file2.js
 M src/.../file3.js
 ....

Watch multiple $scope attributes

A slightly safer solution to combine values might be to use the following as your $watch function:

function() { return angular.toJson([item1, item2]) }

or

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

C++ Double Address Operator? (&&)

This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".

Class vs. static method in JavaScript

There are tree ways methods and properties are implemented on function or class objects, and on they instances.

  1. On the class (or function) itself : Foo.method() or Foo.prop. Those are static methods or properties
  2. On its prototype : Foo.prototype.method() or Foo.prototype.prop. When created, the instances will inherit those object via the prototype witch is {method:function(){...}, prop:...}. So the foo object will receive, as prototype, a copy of the Foo.prototype object.
  3. On the instance itself : the method or property is added to the object itself. foo={method:function(){...}, prop:...}

The this keyword will represent and act differently according to the context. In a static method, it will represent the class itself (witch is after all an instance of Function : class Foo {} is quite equivalent to let Foo = new Function({})

With ECMAScript 2015, that seems well implemented today, it is clearer to see the difference between class (static) methods and properties, instance methods and properties and own methods ans properties. You can thus create three method or properties having the same name, but being different because they apply to different objects, the this keyword, in methods, will apply to, respectively, the class object itself and the instance object, by the prototype or by its own.

class Foo {
  constructor(){super();}
  
  static prop = "I am static" // see 1.
  static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
  
  prop="I am of an instance"; // see 2.
  method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}

var foo= new Foo();
foo.prop = "I am of own";  // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

Best Practice to Use HttpClient in Multithreaded Environment

Definitely Method A because its pooled and thread safe.

If you are using httpclient 4.x, the connection manager is called ThreadSafeClientConnManager. See this link for further details (scroll down to "Pooling connection manager"). For example:

    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, registry);
    HttpClient client = new DefaultHttpClient(cm, params);

Comparison between Corona, Phonegap, Titanium

My understanding of PhoneGap is that they provide Javascript APIs to much of the iPhone APIs.

Titanium seems easier for a web developer background. It is a simple XML file to create a basic TabView application and then everything in the content area is controlled by HTML / JS. I also know that Titanium does provide some javascript access to some of the frameworks (particularly access to location information, the phone ID, etc).

UPDATE: Titanium added Maps API in version 0.8 of their framework.

CSS selector for first element with class

To match your selector, the element must have a class name of red and must be the first child of its parent.

<div>
    <span class="red"></span> <!-- MATCH -->
</div>

<div>
    <span>Blah</span>
    <p class="red"></p> <!-- NO MATCH -->
</div>

<div>
    <span>Blah</span>
    <div><p class="red"></p></div> <!-- MATCH -->
</div>

Convert pyQt UI to python

You don't have to install PyQt4 with all its side features, you just need the PyQt4 package itself. Inside the package you could use the module pyuic.py ("C:\Python27\Lib\site-packages\PyQt4\uic") to convert your Ui file.

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py -help

update python3: use pyuic5 -help # add filepath if needed. pyuic version = 4 or 5.

You will get all options listed:

Usage: pyuic4 [options] <ui-file>

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -p, --preview         show a preview of the UI instead of generating code
  -o FILE, --output=FILE
                        write generated code to FILE instead of stdout
  -x, --execute         generate extra code to test and display the class
  -d, --debug           show debug output
  -i N, --indent=N      set indent width to N spaces, tab if N is 0 [default:
                        4]
  -w, --pyqt3-wrapper   generate a PyQt v3 style wrapper

  Code generation options:
    --from-imports      generate imports relative to '.'
    --resource-suffix=SUFFIX
                        append SUFFIX to the basename of resource files
                        [default: _rc]

So your command will look like this:

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py test_dialog.ui -o test.py -x

You could also use full file paths to your file to convert it.

Why do you want to convert it anyway? I prefer creating widgets in the designer and implement them with via the *.ui file. That makes it much more comfortable to edit it later. You could also write your own widget plugins and load them into the Qt Designer with full access. Having your ui hard coded doesn't makes it very flexible.

I reuse a lot of my ui's not only in Maya, also for Max, Nuke, etc.. If you have to change something software specific, you should try to inherit the class (with the parented ui file) from a more global point of view and patch or override the methods you have to adjust. That saves a lot of work time. Let me know if you have more questions about it.

How come I can't remove the blue textarea border in Twitter Bootstrap?

This is what worked for me.. All the other solutions didn't quite work for me, but I understood one thing from the other solutions and its that default styles of textarea and label in combination is responsible for the blue border.

textarea, label
{
    outline:0px !important;

    -webkit-box-shadow: none !important;
}

EDIT: I had this issue with Ant Design textarea. Thats why this solution worked for me. So, if you are using Ant, then use this.

Difference between \b and \B in regex

Source © Copyright RexEgg.com

Word Boundary: \b*

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

The regex \bcat\b would, therefore, match cat in a black cat, but it wouldn't match it in catatonic, tomcat or certificate. Removing one of the boundaries, \bcat would match cat in catfish, and cat\b would match cat in tomcat, but not vice-versa. Both, of course, would match cat on its own.

Not-a-word-boundary: \B

\B matches all positions where \b doesn't match. Therefore, it matches:

? When neither side is a word character, for instance at any position in the string $=(@-%++) (including the beginning and end of the string)

? When both sides are a word character, for instance between the H and the i in Hi!

This may not seem very useful, but sometimes \B is just what you want. For instance,

? \Bcat\B will find cat fully surrounded by word characters, as in certificate, but neither on its own nor at the beginning or end of words.

? cat\B will find cat both in certificate and catfish, but neither in tomcat nor on its own.

? \Bcat will find cat both in certificate and tomcat, but neither in catfish nor on its own.

? \Bcat|cat\B will find cat in embedded situation, e.g. in certificate, catfish or tomcat, but not on its own.

Checking Bash exit status of several commands efficiently

Checking status in functional manner

assert_exit_status() {

  lambda() {
    local val_fd=$(echo $@ | tr -d ' ' | cut -d':' -f2)
    local arg=$1
    shift
    shift
    local cmd=$(echo $@ | xargs -E ':')
    local val=$(cat $val_fd)
    eval $arg=$val
    eval $cmd
  }

  local lambda=$1
  shift

  eval $@
  local ret=$?
  $lambda : <(echo $ret)

}

Usage:

assert_exit_status 'lambda status -> [[ $status -ne 0 ]] && echo Status is $status.' lls

Output

Status is 127

How can I show three columns per row?

Try this one using Grid Layout:

_x000D_
_x000D_
.grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: auto auto auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
  background-color: rgba(255, 255, 255, 0.8);_x000D_
  border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
  padding: 20px;_x000D_
  font-size: 30px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
  <div class="grid-item">1</div>_x000D_
  <div class="grid-item">2</div>_x000D_
  <div class="grid-item">3</div>  _x000D_
  <div class="grid-item">4</div>_x000D_
  <div class="grid-item">5</div>_x000D_
  <div class="grid-item">6</div>  _x000D_
  <div class="grid-item">7</div>_x000D_
  <div class="grid-item">8</div>_x000D_
  <div class="grid-item">9</div>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

How to put two divs side by side

This is just a simple(not-responsive) HTML/CSS translation of the wireframe you provided.

enter image description here

HTML

<div class="container">

  <header>
    <div class="logo">Logo</div>
    <div class="menu">Email/Password</div>
  </header>

  <div class="first-box">
    <p>Video Explaning Site</p>
  </div>

  <div class="second-box">
    <p>Sign up Info</p>
  </div>

  <footer>
    <div>Website Info</div>
  </footer>

</div>

CSS

.container {
  width:900px; 
  height: 150px;
}

header {
  width:900px; 
  float:left; 
  background: pink; 
  height: 50px;
}

.logo {
  float: left;
  padding: 15px
}

.menu {
  float: right;
  padding: 15px
}

.first-box {
  width:300px; 
  float:left; 
  background: green; 
  height: 150px;
  margin: 50px
}

.first-box p {
  color: #ffffff;
  padding-left: 80px;
  padding-top: 50px;
}

.second-box {
  width:300px; 
  height: 150px; 
  float:right; 
  background: blue;
  margin: 50px
}

.second-box p {
  color: #ffffff;
  padding-left: 110px;
  padding-top: 50px;
}

footer {
  width:900px; 
  float:left; 
  background: black; 
  height: 50px;
  color: #ffffff;
}

footer div {
  padding: 15px;
}

How to create an array of object literals in a loop?

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

IntelliJ Organize Imports

Goto Help -> Find Action (Short Cut for this is Cntl + Shift + A) and type Optimize imports (Short cut for this is Cntl + Alt + O)

Can I set a breakpoint on 'memory access' in GDB?

watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.

You can set read watchpoints on memory locations:

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface

but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:

gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.

So you have to expand them yourself:

gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()

Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.

gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

How to redirect to the same page in PHP

I use correctly in localhost:

header('0');

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

How to add multiple columns to pandas dataframe in one assignment?

I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).

Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.

Here are several approaches that will work:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'col_1': [0, 1, 2, 3],
    'col_2': [4, 5, 6, 7]
})

Then one of the following:

1) Three assignments in one, using list unpacking:

df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]

2) DataFrame conveniently expands a single row to match the index, so you can do this:

df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

3) Make a temporary data frame with new columns, then combine with the original data frame later:

df = pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3]], 
            index=df.index, 
            columns=['column_new_1', 'column_new_2', 'column_new_3']
        )
    ], axis=1
)

4) Similar to the previous, but using join instead of concat (may be less efficient):

df = df.join(pd.DataFrame(
    [[np.nan, 'dogs', 3]], 
    index=df.index, 
    columns=['column_new_1', 'column_new_2', 'column_new_3']
))

5) Using a dict is a more "natural" way to create the new data frame than the previous two, but the new columns will be sorted alphabetically (at least before Python 3.6 or 3.7):

df = df.join(pd.DataFrame(
    {
        'column_new_1': np.nan,
        'column_new_2': 'dogs',
        'column_new_3': 3
    }, index=df.index
))

6) Use .assign() with multiple column arguments.

I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:

df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)

7) This is interesting (based on https://stackoverflow.com/a/44951376/3830997), but I don't know when it would be worth the trouble:

new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols)   # add empty cols
df[new_cols] = new_vals  # multi-column assignment works for existing cols

8) In the end it's hard to beat three separate assignments:

df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3

Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame

How to iterate using ngFor loop Map containing key as string and values as map iteration

The below code useful to display in the map insertion order.

<ul>
    <li *ngFor="let recipient of map | keyvalue: asIsOrder">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

.ts file add the below code.

asIsOrder(a, b) {
    return 1;
}

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Why won't bundler install JSON gem?

Run this command then everything will be ok

sudo apt-get install libgmp-dev

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

the message means you are doing another insert with the same combination of columns that are part of the IDX_STOCK_PRODUCT, which seams to be defined as UNIQUE. If it is so, it doesn't allow to enter same combination (it seems like it consists of two fields) twice.

If you are inserting records, make sure you are picking brand new record id or that the combination of record id and the other column is unique.

Without detailed table structure and your code, we can hardly guess whats going wrong.

How to compile a 64-bit application using Visual C++ 2010 Express?

Programming in a 64-bit environment is quite different than 32-bit environment. Code generated has totally different assembly constitution in 32 & 64-bit code, even the protocols of communicating with functions change. So you can't generate 64-bit code using 32-bit compiler.

You might want to see an article on Microsoft's web site about targeting a 64-bit target but using a 32-bit development machine.

How to deploy correctly when using Composer's develop / production switch?

On production servers I rename vendor to vendor-<datetime>, and during deployment will have two vendor dirs.

A HTTP cookie causes my system to choose the new vendor autoload.php, and after testing I do a fully atomic/instant switch between them to disable the old vendor dir for all future requests, then I delete the previous dir a few days later.

This avoids any problem caused by filesystem caches I'm using in apache/php, and also allows any active PHP code to continue using the previous vendor dir.


Despite other answers recommending against it, I personally run composer install on the server, since this is faster than rsync from my staging area (a VM on my laptop).

I use --no-dev --no-scripts --optimize-autoloader. You should read the docs for each one to check if this is appropriate on your environment.

What is the (function() { } )() construct in JavaScript?

That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.

Most Common Use-case:

One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.

In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.

(function () { 
    var count = 10;
})();
console.log(count);  // Reference Error: count is not defined

ES6 Alternative (Recommended)

In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).

Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.

{ 
    let count = 10;
}
console.log(count);  // ReferenceError: count is not defined

In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.

I call it a “Curly Jail”.

How do I write a Windows batch script to copy the newest file from a directory?

I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:

cp `ls -t1 | head -1` /somedir/

Which will list all files in the current directory sorted by modification time and then cp the most recent to /somedir/

Checking if a key exists in a JS object

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.

How to center a component in Material-UI and make it responsive?

All you have to do is wrap your content inside a Grid Container tag, specify the spacing, then wrap the actual content inside a Grid Item tag.

 <Grid container spacing={24}>
    <Grid item xs={8}>
      <leftHeaderContent/>
    </Grid>

    <Grid item xs={3}>
      <rightHeaderContent/>
    </Grid>
  </Grid>

Also, I've struggled with material grid a lot, I suggest you checkout flexbox which is built into CSS automatically and you don't need any addition packages to use. Its very easy to learn.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Event detect when css property changed using Jquery

Note

Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.

Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.

Try something along these lines:

document.documentElement.addEventListener('DOMAttrModified', function(e){
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

document.documentElement.style.display = 'block';

You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified. It should allow to detect style changes reliably.

jQuery add class .active on menu

I am guessing you are trying to mix Asp code and JS code and at some point it's breaking or not excusing the binding calls correctly.

Perhaps you can try using a delegate instead. It will cut out the complexity of when to bind the click event.

An example would be:

$('body').delegate('.menu li','click',function(){
   var $li = $(this);

   var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;

   if(shouldAddClass){
       $li.addClass('active');
   }
});

See if that helps, it uses the Attribute Starts With Selector from jQuery.

Chi

Find the number of employees in each department - SQL Oracle

SELECT d.DEPTNO
    , d.dname
    , COUNT(e.ename) AS count
FROM   emp e
      INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
      , d.dname;

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Well, you can compute the height of a tree with the following recursive function:

int height(struct tree *t) {
    if (t == NULL)
        return 0;
    else
        return max(height(t->left), height(t->right)) + 1;
}

with an appropriate definition of max() and struct tree. You should take the time to figure out why this corresponds to the definition based on path-length that you quote. This function uses zero as the height of the empty tree.

However, for something like an AVL tree, I don't think you actually compute the height each time you need it. Instead, each tree node is augmented with a extra field that remembers the height of the subtree rooted at that node. This field has to be kept up-to-date as the tree is modified by insertions and deletions.

I suspect that, if you compute the height each time instead of caching it within the tree like suggested above, that the AVL tree shape will be correct, but it won't have the expected logarithmic performance.

How to find files modified in last x minutes (find -mmin does not work as expected)

The problem is that

find . -mmin -60

outputs:

.
./file1
./file2

Note the line with one dot?
That makes ls list the whole directory exactly the same as when ls -l . is executed.

One solution is to list only files (not directories):

find . -mmin -60 -type f | xargs ls -l

But it is better to use directly the option -exec of find:

find . -mmin -60 -type f -exec ls -l {} \;

Or just:

find . -mmin -60 -type f -ls

Which, by the way is safe even including directories:

find . -mmin -60 -ls

How can I use a reportviewer control in an asp.net mvc 3 razor view?

Here is the complete solution for directly integrating a report-viewer control (as well as any asp.net server side control) in an MVC .aspx view, which will also work on a report with multiple pages (unlike Adrian Toman's answer) and with AsyncRendering set to true, (based on "Pro ASP.NET MVC Framework" by Steve Sanderson).

What one needs to do is basically:

  1. Add a form with runat = "server"

  2. Add the control, (for report-viewer controls it can also sometimes work even with AsyncRendering="True" but not always, so check in your specific case)

  3. Add server side scripting by using script tags with runat = "server"

  4. Override the Page_Init event with the code shown below, to enable the use of PostBack and Viewstate

Here is a demonstration:

<form ID="form1" runat="server">
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" />
</form>
<script runat="server">
    protected void Page_Init(object sender, EventArgs e)
    {
        Context.Handler = Page;
    }
    //Other code needed for the report viewer here        
</script>

It is of course recommended to fully utilize the MVC approach, by preparing all needed data in the controller, and then passing it to the view via the ViewModel.

This will allow reuse of the View!

However this is only said for data this is needed for every post back, or even if they are required only for initialization if it is not data intensive, and the data also has not to be dependent on the PostBack and ViewState values.

However even data intensive can sometimes be encapsulated into a lambda expression and then passed to the view to be called there.

A couple of notes though:

  • By doing this the view essentially turns into a web form with all it's drawbacks, (i.e. Postbacks, and the possibility of non Asp.NET controls getting overriden)
  • The hack of overriding Page_Init is undocumented, and it is subject to change at any time

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

When this error occured I first clicked retry for few times and waited for 2 minutes and clicked 'retry' then it installed without any error.(for 2 minutes I was searching to solve this problem online).

How to convert string to binary?

You can access the code values for the characters in your string using the ord() built-in function. If you then need to format this in binary, the string.format() method will do the job.

a = "test"
print(' '.join(format(ord(x), 'b') for x in a))

(Thanks to Ashwini Chaudhary for posting that code snippet.)

While the above code works in Python 3, this matter gets more complicated if you're assuming any encoding other than UTF-8. In Python 2, strings are byte sequences, and ASCII encoding is assumed by default. In Python 3, strings are assumed to be Unicode, and there's a separate bytes type that acts more like a Python 2 string. If you wish to assume any encoding other than UTF-8, you'll need to specify the encoding.

In Python 3, then, you can do something like this:

a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))

The differences between UTF-8 and ascii encoding won't be obvious for simple alphanumeric strings, but will become important if you're processing text that includes characters not in the ascii character set.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How to force a checkbox and text on the same line?

Try this CSS:

label {
  display: inline-block;
}

How to configure slf4j-simple

I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.

I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.

Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.

And I can't change the maven logging config.

So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
    try
    {
        Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger");  //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
        Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
        f.setAccessible(true);
        f.set(l, LocationAwareLogger.WARN_INT);
    }
    catch (Exception e)
    {
        getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
    }

Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.

How to terminate a python subprocess launched with shell=True

what i feel like we could use:

import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

os.killpg(os.getpgid(pro.pid), signal.SIGINT)

this will not kill all your task but the process with the p.pid

Javascript dynamic array of strings

As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9,10,11


var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9

You can even add elements like

var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

you can even change the values

myArray[2] = 40

Printing Order

If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.

Page Submission

If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.

How to set session variable in jquery?

You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

sessionStorage.setItem("username", "John");

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

Verify if file exists or not in C#

This may help you.

try
   {
       con.Open();
       if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
       {
           filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
           ext = System.IO.Path.GetExtension(filename).ToLower();
           string str=@"/Resumes/" + filename;
           saveloc = (Server.MapPath(".") + str);
           string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
           for (int i = 0; i < exts.Length; i++)
           {
               if (ext == exts[i])
                   fileok = true;
           }
           if (fileok)
           {
               if (File.Exists(saveloc))
                   throw new Exception(Label1.Text="File exists!!!");
               fileUpload1.PostedFile.SaveAs(saveloc);
               cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
               cmd.ExecuteNonQuery();
               Label1.Text = "Upload Successful!!!";
               Label1.ForeColor = System.Drawing.Color.Blue;
               con.Close();
           }
           else
           {
               Label1.Text = "Upload not successful!!!";
               Label1.ForeColor = System.Drawing.Color.Red;
           }
       }

    }
   catch (Exception ee) { Label1.Text = ee.Message; }

htaccess remove index.php from url

For more detail

create .htaccess file on project root directory and put below code for remove index.php

  RewriteEngine on
  RewriteCond $1 !^(index.php|resources|robots.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Show week number with Javascript?

In case you already use jquery-ui (specifically datepicker):

Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }

Usage:

var myDate = new Date();
myDate.getWeek();

More here: UI/Datepicker/iso8601Week

I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jquery-ui this might just be a simple fit for someone - as it was for me.

angularjs: ng-src equivalent for background-image:url(...)

I've found with 1.5 components that abstracting the styling from the DOM to work best in my async situation.

Example:

<div ng-style="{ 'background': $ctrl.backgroundUrl }"></div>

And in the controller, something likes this:

this.$onChanges = onChanges;

function onChanges(changes) {
    if (changes.value.currentValue){
        $ctrl.backgroundUrl = setBackgroundUrl(changes.value.currentValue);
    }
}

function setBackgroundUrl(value){
    return 'url(' + value.imgUrl + ')';
}

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

Switch statement fallthrough in C#?

Just a quick note to add that the compiler for Xamarin actually got this wrong and it allows fallthrough. It has supposedly been fixed, but has not been released. Discovered this in some code that actually was falling through and the compiler did not complain.

Append lines to a file using a StreamWriter

I assume you are executing all of the above code each time you write something to the file. Each time the stream for the file is opened, its seek pointer is positioned at the beginning so all writes end up overwriting what was there before.

You can solve the problem in two ways: either with the convenient

file2 = new StreamWriter("c:/file.txt", true);

or by explicitly repositioning the stream pointer yourself:

file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);

Using setTimeout to delay timing of jQuery actions

This is how I solved the problem The menu closes a few seconds after mouse out (that if hover didn't fire),

//Set timer switch
$setM_swith=0;

$(function(){
    $(".navbar-nav li a").click(function(event) {
        if (!$(this).parent().hasClass('dropdown'))
            $(".navbar-collapse").collapse('hide');
    });
    $(".navbar-collapse").mouseleave(function(){
        $setM_swith=1;
        setTimeout(function(){ 
           if($setM_swith==1) {
             $(".navbar-collapse").collapse('hide');
             $setM_swith=0;} 
        }, 3000);
    });
    $(".navbar-collapse").mouseover(function() {
        $setM_swith=0;
    });
 });

Difference between <input type='button' /> and <input type='submit' />

<input type="button" /> buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.

<input type="submit"> buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.

How do I update/upsert a document in Mongoose?

Mongoose now supports this natively with findOneAndUpdate (calls MongoDB findAndModify).

The upsert = true option creates the object if it doesn't exist. defaults to false.

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

In older versions Mongoose does not support these hooks with this method:

  • defaults
  • setters
  • validators
  • middleware

Editing an item in a list<T>

You don't need to use linq since List<T> provides the methods to do this:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}