Programs & Examples On #Unsafe pointers

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

jQuery post() with serialize and extra data

$.ajax({    
    type: 'POST',  
    url: 'test.php',  
    data:$("#Test-form").serialize(),  
    dataType:'json',
     beforeSend:function(xhr, settings){
     settings.data += '&moreinfo=MoreData';
     },
    success:function(data){
            //  json response  
    },
    error: function(data) { 
        // if error occured
    }
    });

Disable resizing of a Windows Forms form

  1. First, select the form.
  2. Then, go to the properties menu.
  3. And change the property "FormBorderStyle" from sizable to Fixed3D or FixedSingle.

    This is where to modify the property "FormBorderStyle".

What's wrong with nullable columns in composite primary keys?

NULL == NULL -> false (at least in DBMSs)

So you wouldn't be able to retrieve any relationships using a NULL value even with additional columns with real values.

Remove all the children DOM elements in div

while(node.firstChild) {
    node.removeChild(node.firstChild);
}

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Make sure that the column values u added in entity class having get set properties also in the same order which is present in target table.

Effective swapping of elements of an array in Java

inplace swapping (incase you already didn't know) can save a bit of space by not creating a temp variable.

arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];

How do I get the coordinate position after using jQuery drag and drop?

This worked for me:

$("#element1").droppable(
{
    drop: function(event, ui)
    {
        var currentPos = ui.helper.position();
            alert("left="+parseInt(currentPos.left)+" top="+parseInt(currentPos.top));
    }
});

Show and hide divs at a specific time interval using jQuery

Working Example here - add /edit to the URL to play with the code

You just need to use JavaScript setInterval function

_x000D_
_x000D_
$('html').addClass('js');_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  var timer = setInterval(showDiv, 5000);_x000D_
_x000D_
  var counter = 0;_x000D_
_x000D_
  function showDiv() {_x000D_
    if (counter == 0) {_x000D_
      counter++;_x000D_
      return;_x000D_
    }_x000D_
_x000D_
    $('div', '#container')_x000D_
      .stop()_x000D_
      .hide()_x000D_
      .filter(function() {_x000D_
        return this.id.match('div' + counter);_x000D_
      })_x000D_
      .show('fast');_x000D_
    counter == 3 ? counter = 0 : counter++;_x000D_
_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
  <title>Sandbox</title>_x000D_
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />_x000D_
  <style type="text/css" media="screen">_x000D_
    body {_x000D_
      background-color: #fff;_x000D_
      font: 16px Helvetica, Arial;_x000D_
      color: #000;_x000D_
    }_x000D_
    _x000D_
    .display {_x000D_
      width: 300px;_x000D_
      height: 200px;_x000D_
      border: 2px solid #000;_x000D_
    }_x000D_
    _x000D_
    .js .display {_x000D_
      display: none;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h2>Example of using setInterval to trigger display of Div</h2>_x000D_
  <p>The first div will display after 10 seconds...</p>_x000D_
  <div id='container'>_x000D_
    <div id='div1' class='display' style="background-color: red;">_x000D_
      div1_x000D_
    </div>_x000D_
    <div id='div2' class='display' style="background-color: green;">_x000D_
      div2_x000D_
    </div>_x000D_
    <div id='div3' class='display' style="background-color: blue;">_x000D_
      div3_x000D_
    </div>_x000D_
    <div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT:

In response to your comment about the container div, just modify this

$('div','#container')

to this

$('#div1, #div2, #div3')

How to check java bit version on Linux?

Run java with -d64 or -d32 specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.

Explicit vs implicit SQL joins

On some databases (notably Oracle) the order of the joins can make a huge difference to query performance (if there are more than two tables). On one application, we had literally two orders of magnitude difference in some cases. Using the inner join syntax gives you control over this - if you use the right hints syntax.

You didn't specify which database you're using, but probability suggests SQL Server or MySQL where there it makes no real difference.

how to delete installed library form react native project

you have to check your linked project, in the new version of RN, don't need to link if you linked it cause a problem, I Fixed the problem by unlinked manually the dependency that I linked and re-run.

Replace \n with <br />

You could also have problems if the string has <, > or & chars in it, etc. Pass it to cgi.escape() to deal with those.

http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape

DROP IF EXISTS VS DROP?

DROP TABLE IF EXISTS [table_name]

it first checks if the table exists, if it does it deletes the table while

DROP TABLE [table_name]

it deletes without checking, so if it doesn't exist it exits with an error

Safe Area of Xcode 9

enter image description here

  • Earlier in iOS 7.0–11.0 <Deprecated> UIKit uses the topLayoutGuide & bottomLayoutGuide which is UIView property
  • iOS11+ uses safeAreaLayoutGuide which is also UIView property

  • Enable Safe Area Layout Guide check box from file inspector.

  • Safe areas help you place your views within the visible portion of the overall interface.

  • In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.

  • safeAreaLayoutGuide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor viewss.
  • Use safe areas as an aid to laying out your content like UIButton etc.

  • When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

  • Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.

  • The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones

  • Height of home indicator container is 34 points.

  • Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.

enter image description here

You can set constraints with respective of self.view.safeAreaLayoutGuide as-

ObjC:

  self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
    [self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
    [self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
    [self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;

Swift:

   demoView.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
        } else {
            NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
        }

enter image description here

enter image description here

enter image description here

Best way to incorporate Volley (or other library) into Android Studio project

For incorporate volley in android studio,

  1. paste the following command in terminal (
    git clone https://android.googlesource.com/platform/frameworks/volley ) and run it.

    Refer android developer tutorial for this.

    It will create a folder name volley in the src directory.
  2. Then go to android studio and right click on the project.
  3. choose New -> Module from the list.
  4. Then click on import existing Project from the below list.
  5. you will see a text input area namely source directory, browse the folder you downloaded (volley) and then click on finish.
  6. you will see a folder volley in your project view.
  7. the switch to android view and open the build:gradle(Module:app) file and append the following line in the dependency area:

    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

  8. Now synchronise your project and also build your project.

How to download a file from my server using SSH (using PuTTY on Windows)

try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop

Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.

Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop

JavaScript get clipboard data on paste event (Cross browser)

The situation has changed since writing this answer: now that Firefox has added support in version 22, all major browsers now support accessing the clipboard data in a paste event. See Nico Burns's answer for an example.

In the past this was not generally possible in a cross-browser way. The ideal would be to be able to get the pasted content via the paste event, which is possible in recent browsers but not in some older browsers (in particular, Firefox < 22).

When you need to support older browsers, what you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and WebKit browsers such as Safari or Chrome. Recent versions of both TinyMCE and CKEditor use this technique:

  1. Detect a ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn designMode off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns designMode back on, restores the user selection and pastes the text in.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the textarea (in some browsers, at least).

In the unlikely event that you need to support Firefox 2, note that you'll need to place the textarea in the parent document rather than the WYSIWYG editor iframe's document in that browser.

How to add two strings as if they were numbers?

If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.

const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"

JSON.Net Self referencing loop detected

I just had the same problem with Parent/Child collections and found that post which has solved my case. I Only wanted to show the List of parent collection items and didn't need any of the child data, therefore i used the following and it worked fine:

JsonConvert.SerializeObject(ResultGroups, Formatting.None,
                        new JsonSerializerSettings()
                        { 
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });

JSON.NET Error Self referencing loop detected for type

it also referes to the Json.NET codeplex page at:

http://json.codeplex.com/discussions/272371

Documentation: ReferenceLoopHandling setting

Getting "cannot find Symbol" in Java project in Intellij

I use maven in my project. For some reason IntelliJ was giving me these kind of wierd errors. I ran mvn clean and tried a resync and these errors disappeared.

C++ string to double conversion

The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.

Compile and run this program, then study it. It is simple

#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;

int main()
{
    // Converting the content of a char array or a string to a double variable
    double d;
    string S;
    S = "4.5";
    istringstream(S) >> d;    
    cout << "\nThe value of the double variable d is " << d << endl;
    istringstream("9.87654") >> d;  
    cout << "\nNow the value of the double variable d is " << d << endl;



    // Converting a double to string with formatting restrictions
    double D=3.771234567;

    ostringstream Q;
    Q.fill('#');
    Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
    S = Q.str(); // formatted converted double is now in string 

    cout << "\nThe value of the string variable S is " << S << endl;
    return 0;
}

Prof. Martinez

Cassandra cqlsh - connection refused

When I installed Cassandra 3.11.1, I came across this problem. I checked the /var/log/cassandra/cassandra.log and found this error Exception encountered during startup....It is a bug and already reported. The original post link https://issues.apache.org/jira/browse/CASSANDRA-14173.

The solution is to downgrade Cassandra to 3.0

  1. download Cassandra rpm

curl -O https://www.apache.org/dist/cassandra/redhat/30x/cassandra-3.0.15-1.noarch.rpm

or

wget https://www.apache.org/dist/cassandra/redhat/30x/cassandra-3.0.15-1.noarch.rpm

  1. rpm -ivh cassandra-3.0.15-1.noarch.rpm
  2. service cassandra start
  3. service cassandra status # check cassandra status

cassandra (pid 2322) is running...

  1. cqlsh # start cassandra

Send JSON data from Javascript to PHP?

This is a summary of the main solutions with easy-to-reproduce code:

Method 1 (application/json or text/plain + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data)); 

PHP side, you can get the data with:

print_r(json_decode(file_get_contents('php://input'), true));

Method 2 (x-www-form-urlencoded + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data))); 

Note: encodeURIComponent(...) is needed for example if the JSON contains & character.

PHP side, you can get the data with:

print_r(json_decode($_POST['json'], true));

Method 3 (x-www-form-urlencoded + URLSearchParams)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString()); 

PHP side, you can get the data with:

print_r($_POST);

Note: https://caniuse.com/#search=URLSearchParams

Insert at first position of a list in Python

Use insert:

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

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

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

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

Get list of databases from SQL Server

Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:

    SELECT  db.[name] as dbname 
    FROM [master].[sys].[databases] db
    LEFT OUTER JOIN  [master].[sys].[sysusers] su on su.sid = db.owner_sid
    WHERE su.sid is null
    order by db.[name]

Asp Net Web API 2.1 get client IP address

Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.

Here's how I solved it:

using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
    {
        var hostname = HttpContext.Current.Request.UserHostAddress;
        IPAddress ipAddress = IPAddress.Parse(hostname);
        IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
        ...

Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?

IE6/IE7 css border on select element

You'd need a custom-designed select box with CSS and JavaScript. You'd need to make absolutely sure it degrades perfectly to a standard select element should a user have JavaScript disabled.

IMO, it's just not worth the effort. Stick with font stylings within the select to make it close to your site's design; leave the borders, etc., to the box elements.

Batch files : How to leave the console window open

You can just put a pause command in the last line of your batch file:

@echo off
echo Hey, I'm just doing some work for you.
pause

Will give you something like this as output:

Hey, I'm just doing some work for you.

Press any key to continue ...

Note: Using the @echo prevents to output the command before the output is printed.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I deleted folders build inside a project. After cleaned and rebuilt it in Android Studio. Then corrected errors in build.gradle and AndroidManifest.

How to read a list of files from a folder using PHP?

There is this function scandir():

$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
    print $files[$i]."<br>";

More here in the php.net manual

String length in bytes in JavaScript

For simple UTF-8 encoding, with slightly better compatibility than TextEncoder, Blob does the trick. Won't work in very old browsers though.

new Blob([""]).size; // -> 4  

How to specify a port number in SQL Server connection string?

For JDBC the proper format is slightly different and as follows:

jdbc:microsoft:sqlserver://mycomputer.test.xxx.com:49843

Note the colon instead of the comma.

What is the use of style="clear:both"?

Just to add to RichieHindle's answer, check out Floatutorial, which walks you through how CSS floating and clearing works.

How do I call an Angular.js filter with multiple arguments?

If you need two or more dealings with the filter, is possible to chain them:

{{ value | decimalRound: 2 | currencySimbol: 'U$' }} 
// 11.1111 becomes U$ 11.11

How to write one new line in Bitbucket markdown?

It's possible, as addressed in Issue #7396:

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return or Enter.

How to automatically generate getters and setters in Android Studio

  • create the variable
  • right click
  • select "Generate" and then select "Getter and Setter" option

Right click menu

MVC razor form with multiple different submit buttons?

You can use JS + Ajax. For example, if you have any button you can say it what it must do on click event. Here the code:

 <input id="btnFilterData" type="button" value="myBtn">

Here your button in html: in the script section, you need to use this code (This section should be at the end of the document):

<script type="text/javascript">
$('#btnFilterData').click(function () {
    myFunc();
});
</script>

And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):

function myFunc() {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "/myController/myFuncOnController",
        data: {
             //params, which you can pass to yu func
        },
        success: function(result) {

        error: function (errorData) {

        }
    });
};

python multithreading wait till all threads finished

I prefer using list comprehension based on an input list:

inputs = [scriptA + argumentsA, scriptA + argumentsB, ...]
threads = [Thread(target=call_script, args=(i)) for i in inputs]
[t.start() for t in threads]
[t.join() for t in threads]

How do I import a namespace in Razor View Page?

Depending on your need you can use one of following method:

How can I switch to another branch in git?

If you want the branch to track the remote branch, which is very important if you're going to commit changes to the branch and pull changes etc, you need to add a -t for the actual checkout like so: git checkout -t branchname

How do I check in python if an element of a list is empty?

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'

When to use React "componentDidUpdate" method?

When something in the state has changed and you need to call a side effect (like a request to api - get, put, post, delete). So you need to call componentDidUpdate() because componentDidMount() is already called.

After calling side effect in componentDidUpdate(), you can set the state to new value based on the response data in the then((response) => this.setState({newValue: "here"})). Please make sure that you need to check prevProps or prevState to avoid infinite loop because when setting state to a new value, the componentDidUpdate() will call again.

There are 2 places to call a side effect for best practice - componentDidMount() and componentDidUpdate()

Select 50 items from list at random to write to file

If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

How to use LINQ Distinct() with multiple fields

This is my solution, it supports keySelectors of different types:

public static IEnumerable<TSource> DistinctBy<TSource>(this IEnumerable<TSource> source, params Func<TSource, object>[] keySelectors)
{
    // initialize the table
    var seenKeysTable = keySelectors.ToDictionary(x => x, x => new HashSet<object>());

    // loop through each element in source
    foreach (var element in source)
    {
        // initialize the flag to true
        var flag = true;

        // loop through each keySelector a
        foreach (var (keySelector, hashSet) in seenKeysTable)
        {                    
            // if all conditions are true
            flag = flag && hashSet.Add(keySelector(element));
        }

        // if no duplicate key was added to table, then yield the list element
        if (flag)
        {
            yield return element;
        }
    }
}

To use it:

list.DistinctBy(d => d.CategoryId, d => d.CategoryName)

How to express a NOT IN query with ActiveRecord/Rails?

Using Arel:

topics=Topic.arel_table
Topic.where(topics[:forum_id].not_in(@forum_ids))

or, if preferred:

topics=Topic.arel_table
Topic.where(topics[:forum_id].in(@forum_ids).not)

and since rails 4 on:

topics=Topic.arel_table
Topic.where.not(topics[:forum_id].in(@forum_ids))

Please notice that eventually you do not want the forum_ids to be the ids list, but rather a subquery, if so then you should do something like this before getting the topics:

@forum_ids = Forum.where(/*whatever conditions are desirable*/).select(:id)

in this way you get everything in a single query: something like:

select * from topic 
where forum_id in (select id 
                   from forum 
                   where /*whatever conditions are desirable*/)

Also notice that eventually you do not want to do this, but rather a join - what might be more efficient.

Write bytes to file

You convert the hex string to a byte array.

public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                 .ToArray();
}

Credit: Jared Par

And then use WriteAllBytes to write to the file system.

using c# .net libraries to check for IMAP messages from gmail servers

I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).

One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).

It's also the only library that I know of that supports threading of messages.

using System;
using System.Net;
using System.Threading;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                using (var cancel = new CancellationTokenSource ()) {
                    client.Connect ("imap.gmail.com", 993, true, cancel.Token);

                    // If you want to disable an authentication mechanism,
                    // you can do so by removing the mechanism like this:
                    client.AuthenticationMechanisms.Remove ("XOAUTH");

                    client.Authenticate ("joey", "password", cancel.Token);

                    // The Inbox folder is always available...
                    var inbox = client.Inbox;
                    inbox.Open (FolderAccess.ReadOnly, cancel.Token);

                    Console.WriteLine ("Total messages: {0}", inbox.Count);
                    Console.WriteLine ("Recent messages: {0}", inbox.Recent);

                    // download each message based on the message index
                    for (int i = 0; i < inbox.Count; i++) {
                        var message = inbox.GetMessage (i, cancel.Token);
                        Console.WriteLine ("Subject: {0}", message.Subject);
                    }

                    // let's try searching for some messages...
                    var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
                        .And (SearchQuery.SubjectContains ("MailKit"))
                        .And (SearchQuery.Seen);

                    foreach (var uid in inbox.Search (query, cancel.Token)) {
                        var message = inbox.GetMessage (uid, cancel.Token);
                        Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
                    }

                    client.Disconnect (true, cancel.Token);
                }
            }
        }
    }
}

How to make inline plots in Jupyter Notebook larger?

The question is about matplotlib, but for the sake of any R users that end up here given the language-agnostic title:

If you're using an R kernel, just use:

options(repr.plot.width=4, repr.plot.height=3)

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

This issue (https://bugs.eclipse.org/394042) is fixed in m2e 1.5.0 which is available for Eclipse Kepler and Luna from this p2 repo :

http://download.eclipse.org/technology/m2e/releases/1.5

If you also use m2e-wtp, you'll need to install m2e-wtp 1.1.0 as well :

http://download.eclipse.org/m2e-wtp/releases/luna/1.1

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Finally I found answer myself. To add new icons in 2.3.2 bootstrap we have to add Font Awsome css in you file. After doing this we can override the styles with css to change the color and size.

<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

CSS

.brown{color:#9b846b}

If we want change the color of icon then just add brown class and icon will turn in brown color. It also provide icon of various size.

HTML

<p><i class="icon-camera-retro icon-large brown"></i> icon-camera-retro</p> <!--brown class added-->
<p><i class="icon-camera-retro icon-2x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-3x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-4x"></i> icon-camera-retro</p>

How to set a JVM TimeZone Properly

Setting environment variable TZ should also works

ex: export TZ=Asia/Shanghai

Ansible: deploy on multiple hosts in the same time

Check out this POC or MVP of running in parallel one-host-from-every-group (for all hosts) https://github.com/sirkubax/szkolenie3/tree/master/playbooks/playgroups

you may get the inspiration

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How do I use this JavaScript variable in HTML?

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

_x000D_
_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
</script>_x000D_
<body>_x000D_
  <p id="a"></p>_x000D_
  <p id="b"></p>_x000D_
  <script>_x000D_
    document.getElementById('a').innerHTML = name;_x000D_
document.querySelector('#b').innerHTML = name.length;</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

What is the best way to get the minimum or maximum value from an Array of numbers?

Please take into account that sorting the array will only be faster that looping up to certain size of the array. If your array is small (and it will be like that any time) then your solution is perfectly fine. But if it might get too large you should use a conditional to use the sort approach when the array is small, and the normal iteration when it is too large

How do I change the android actionbar title and icon

You can also do as follow :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        setSupportActionBar(toolbar)
        setTitle("Activity 2")
    }

How to shut down the computer from C#

Note that shutdown.exe is just a wrapper around InitiateSystemShutdownEx, which provides some niceties missing in ExitWindowsEx

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Show popup after page load

If you don't want to use jquery, use this:

<script>
 // without jquery
document.addEventListener("DOMContentLoaded", function() {
 setTimeout(function() {
  // run your open popup function after 5 sec = 5000
  PopUp();
 }, 5000)
});
</script>

OR With jquery

<script>
  $(document).ready(function(){
   setTimeout(function(){
   // open popup after 5 seconds
   PopUp();
  },5000);  
 });
</script>

Get value from hashmap based on key to JSTL

I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on

<c:forEach items="${requestScope.key}"  var="map" varStatus="status" >
    <c:if test="${status.index eq 1}">
        <option><c:out value=${map.value}/></option>
    </c:if>
</c:forEach>    

Merge (Concat) Multiple JSONObjects in Java

For me that function worked:

private static JSONObject concatJSONS(JSONObject json, JSONObject obj) {
    JSONObject result = new JSONObject();

    for(Object key: json.keySet()) {
        System.out.println("adding " + key + " to result json");
        result.put(key, json.get(key));
    }

    for(Object key: obj.keySet()) {
        System.out.println("adding " + key + " to result json");
        result.put(key, obj.get(key));
    }

    return result;
}

(notice) - this implementation of concataion of json is for import org.json.simple.JSONObject;

Single vs Double quotes (' vs ")

Double quotes are used for strings (i.e., "this is a string") and single quotes are used for a character (i.e., 'a', 'b' or 'c'). Depending on the programming language and context, you can get away with using double quotes for a character but not single quotes for a string.

HTML doesn't care about which one you use. However, if you're writing HTML inside a PHP script, you should stick with double quotes as you will need to escape them (i.e., \"whatever\") to avoid confusing yourself and PHP.

'this' is undefined in JavaScript class methods

JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:

Ninja = function (name) {
    this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'

enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'

Note that Ninja instances have the same properties but aNinja cannot access the properties of enemyNinja. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype:

Ninja.prototype.jump = function () {
   return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'

Calling this directly will throw an error because this only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window in a browser)

How to display default text "--Select Team --" in combo box on pageload in WPF?

Based on IceForge's answer I prepared a reusable solution:

xaml style:

<Style x:Key="ComboBoxSelectOverlay" TargetType="TextBlock">
    <Setter Property="Grid.ZIndex" Value="10"/>
    <Setter Property="Foreground" Value="{x:Static SystemColors.GrayTextBrush}"/>
    <Setter Property="Margin" Value="6,4,10,0"/>
    <Setter Property="IsHitTestVisible" Value="False"/>
    <Setter Property="Visibility" Value="Hidden"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding}" Value="{x:Null}">
            <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

example of use:

<Grid>
     <ComboBox x:Name="cmb"
               ItemsSource="{Binding Teams}" 
               SelectedItem="{Binding SelectedTeam}"/>
     <TextBlock DataContext="{Binding ElementName=cmb,Path=SelectedItem}"
               Text=" -- Select Team --" 
               Style="{StaticResource ComboBoxSelectOverlay}"/>
</Grid>

Iterating through populated rows

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next

Relation between CommonJS, AMD and RequireJS?

AMD

  • introduced in JavaScript to scale JavaScript project into multiple files
  • mostly used in browser based application and libraries
  • popular implementation is RequireJS, Dojo Toolkit

CommonJS:

  • it is specification to handle large number of functions, files and modules of big project
  • initial name ServerJS introduced in January, 2009 by Mozilla
  • renamed in August, 2009 to CommonJS to show the broader applicability of the APIs
  • initially implementation were server, nodejs, desktop based libraries

Example

upper.js file

exports.uppercase = str => str.toUpperCase()

main.js file

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

Summary

  • AMD – one of the most ancient module systems, initially implemented by the library require.js.
  • CommonJS – the module system created for Node.js server.
  • UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Resources:

What are the best use cases for Akka framework

We are using akka with its camel plugin to distribute our analysis and trending processing for twimpact.com. We have to process between 50 and 1000 messages per second. In addition to multi-node processing with camel it is also used to distribute work on a single processor to multiple workers for maximum performance. Works quite well, but requires some understanding of how to handle congestions.

Null vs. False vs. 0 in PHP

I have just wasted 1/2 a day trying to get either a 0, null, false to return from strops!

Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:

Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.

Anyway here was the basis of the cosing:

if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) 
{ 
    do this 
} else {
    or that
}

{
echo strpos(mydomain.co.uk, mydomain);  

if ( strpos(mydomain, xmas) == null ) 
    {
        echo "\n1 is null"; 
    }

if ( (strpos(mydomain.co.uk, mydomain)) == 0 ) 
    {
        echo "\n2 is 0"; 
    } else {
        echo "\n2 Something is WRONG"; 
    }

if ( (mydomain.co.uk, mydomain)) != 0 ) 
    {
        echo "\n3 is 0"; 
    } else {
        echo "\n3 it is not 0"; 
    }

if ( (mydomain.co.uk, mydomain)) == null ) 
    {
        echo "\n4 is null"; 
    } else {
        echo "\n4 Something is WRONG"; 
    }
}

FINALLY after reading this Topic, I found that this worked!!!

{
if ((mydomain.co.uk, mydomain)) !== false ) 
    {
        echo "\n5 is True"; 
    } else {
        echo "\n5 is False"; 
    }
}

Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false, as its also can be a NULL day!

After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False, NULL and 0 are not all the same as True or False or NULL?

Having Django serve downloadable files

S.Lott has the "good"/simple solution, and elo80ka has the "best"/efficient solution. Here is a "better"/middle solution - no server setup, but more efficient for large files than the naive fix:

http://djangosnippets.org/snippets/365/

Basically, Django still handles serving the file but does not load the whole thing into memory at once. This allows your server to (slowly) serve a big file without ramping up the memory usage.

Again, S.Lott's X-SendFile is still better for larger files. But if you can't or don't want to bother with that, then this middle solution will gain you better efficiency without the hassle.

How can I color a UIImage in Swift?

Since I found Darko's answer very helpful in colorizing custom pins for mapView annotations, but had to do some conversions for Swift 3, thought I'd share the updated code along with my recommendation for his answer:

extension UIImage {
    func maskWithColor(color: UIColor) -> UIImage {

        var maskImage = self.CGImage
        let width = self.size.width
        let height = self.size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        bitmapContext!.clip(to: bounds, mask: maskImage!)
        bitmapContext!.setFillColor(color.cgColor)
        bitmapContext!.fill(bounds)

        let cImage = bitmapContext!.makeImage()
        let coloredImage = UIImage(CGImage: cImage)

        return coloredImage!
    }
}

Creating your own header file in C

foo.h

#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_

foo.c

#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}

main.c

#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}

To compile using GCC

gcc -o my_app main.c foo.c

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

SQL - How do I get only the numbers after the decimal?

Make it very simple by query:

select substr('123.123',instr('123.123','.')+1, length('123.123')) from dual;

Put your number or column name instead 123.122

Getting time and date from timestamp with php

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];

Session only cookies with Javascript

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

What is the size of a pointer?

Pointers are not always the same size on the same architecture.

You can read more on the concept of "near", "far" and "huge" pointers, just as an example of a case where pointer sizes differ...

http://en.wikipedia.org/wiki/Intel_Memory_Model#Pointer_sizes

Finding an elements XPath using IE Developer tool

This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62

Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?

how do I make a single legend for many subplots with matplotlib?

You just have to ask for the legend once, outside of your loop.

For example, in this case I have 4 subplots, with the same lines, and a single legend.

from matplotlib.pyplot import *

ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']

fig = figure()
fig.suptitle('concentration profile analysis')

for a in range(len(ficheiros)):
    # dados is here defined
    level = dados.variables['level'][:]

    ax = fig.add_subplot(2,2,a+1)
    xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h']) 
    ax.set_xlabel('time (hours)')
    ax.set_ylabel('CONC ($\mu g. m^{-3}$)')

    for index in range(len(level)):
        conc = dados.variables['CONC'][4:12,index] * 1e9
        ax.plot(conc,label=str(level[index])+'m')

    dados.close()

ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
         # it will place the legend on the outer right-hand side of the last axes

show()

jQuery remove special characters from string and more

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');

How does one sum only those rows in excel not filtered out?

When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).

So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):

Function SumVis(r As Range)
    Dim cell As Excel.Range
    Dim total As Variant

    For Each cell In r.Cells
        If cell.Height <> 0 Then
            total = total + cell.Value
        End If
    Next

    SumVis = total
End Function

Edit:

You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.

SHA-1 fingerprint of keystore certificate

![Go to far left[![][1][1]

Please refer to the following images and get the SHA-1 key Refresh

View in console panel at bottom

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

Put request with simple string as request body

simply put in headers 'Content-Type': 'application/json' and the sent data in body JSON.stringify(string)

Regex Email validation

STRING SEARCH USING REGEX METHOD IN C#

How to validate an Email by Regular Expression?

string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
{
    Console.WriteLine("Email: {0} is valid.", Email);
}
else
{
    Console.WriteLine("Email: {0} is not valid.", Email);
}

Use Reference String.Regex() Method

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

How do I set the time zone of MySQL?

If anyone is using GoDaddy Shared Hosting, you can try for following solution, worked for me.

When starting DB connection, set the time_zone command in my PDO object e.g.:

$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->exec("SET time_zone='+05:30';");

Where "+05:30" is the TimeZone of India. You can change it as per your need.

After that; all the MySQL processes related to Date and Time are set with required timezone.

Source : https://in.godaddy.com/community/cPanel-Hosting/How-to-change-TimeZone-for-MySqL/td-p/31861

ImageView - have height match width?

To set your ImageView equal to half the screen, you need to add the following to your XML for the ImageView:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"/>

To then set the height equal to this width, you need to do it in code. In the getView method of your GridView adapter, set the ImageView height equal to its measured width:

mImageView.getLayoutParams().height = mImageView.getMeasuredWidth();

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

Displaying the Error Messages in Laravel after being Redirected from controller

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

Determine whether an array contains a value

The simplest solution for a contains function, would be a function that looks like this :

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
}

Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :

var helper = {};

helper.array = {
    contains : function (haystack, needle) {
        return !!~haystack.indexOf(needle);
    }, 
    ...
};

Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf, you could use this polyfill, which I got from the MDN :

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    var o = Object(this);
    var len = o.length >>> 0;
    if (len === 0) {
      return -1;
    }
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }
    if (n >= len) {
      return -1;
    }
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

Read all worksheets in an Excel workbook into an R list with data.frames

Note that most of XLConnect's functions are already vectorized. This means that you can read in all worksheets with one function call without having to do explicit vectorization:

require(XLConnect)
wb <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", package = "XLConnect"))
lst = readWorksheet(wb, sheet = getSheets(wb))

With XLConnect 0.2-0 lst will already be a named list.

How to do SQL Like % in Linq?

I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

or

from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

Return JSON response from Flask view

Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.

@app.route("/")
def index():
    return {
        "api_stuff": "values",
    }

is equivalent to

@app.route("/")
def index():
    return jsonify({
        "api_stuff": "values",
    })

See the pull request that added this: https://github.com/pallets/flask/pull/3111

Rolling back local and remote git repository by 1 commit

You can also do this:

git reset --hard <commit-hash>
git push -f origin master

and have everyone else who got the latest bad commits reset:

git reset --hard origin/master

Ruby value of a hash key?

Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol. So if your hash is similar to

hash = { "key1" => "value1", "key2" => "value2" }

you can access the value with

hash["key1"]

or for

hash = { :key1 => "value1", :key2 => "value2"}

or the new format supported in Ruby 1.9

hash = { key1: "value1", key2: "value2" }

you can access the value with

hash[:key1]

Passing parameters in Javascript onClick event

This will work from JS without coupling to HTML:

document.getElementById("click-button").onclick = onClickFunction;

function onClickFunction()
{
    return functionWithArguments('You clicked the button!');
}

function functionWithArguments(text) {
    document.getElementById("some-div").innerText = text;
}

CSS3 background image transition

The solution (that I found by myself) is a ninja trick, I can offer you two ways:

first you need to make a "container" for the <img>, it will contain normal and hover states at the same time:

<div class="images-container">
    <img src="http://lorempixel.com/400/200/animals/9/">
    <img src="http://lorempixel.com/400/200/animals/10/">
</div>

Basically, you need to hide "normal" state and show their "hover" when you hover it

and that's it, I hope somebody find it useful.

Get an object's class name at runtime

  • Had to add ".prototype." to use : myClass.prototype.constructor.name .
  • Otherwise with the following code : myClass.constructor.name, I had the TypeScript error :

error TS2339: Property 'name' does not exist on type 'Function'.

SQL "between" not inclusive

your code

SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'

how SQL reading it

SELECT * FROM Cases WHERE '2013-05-01 22:25:19' BETWEEN '2013-05-01 00:00:00' AND '2013-05-01 00:00:00'

if you don't mention time while comparing DateTime and Date by default hours:minutes:seconds will be zero in your case dates are the same but if you compare time created_at is 22 hours ahead from your end date range

if the above is clear you fix this in many ways like putting ending hours in your end date eg BETWEEN '2013-05-01' AND ''2013-05-01 23:59:59''

OR

simply cast create_at as date like cast(created_at as date) after casting as date '2013-05-01 22:25:19' will be equal to '2013-05-01 00:00:00'

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Depending on the file which will be put into filesystem, as long as that file is not a malware, then that would be safe.

But don't worry to write/read file(s) to File System directory, cause you can tighten that directory security (include it's inheritance) by give a proper access right and security restriction. eg: read/write/modify.

By default, File System, Local Storage, and Storage directory are located on "\Users[Current User]\AppData\Local\Google\Chrome\User Data\Default" directory.

However you can customize it by using "--user-data-dir" flag.

And this is a sample:

"C:\Program Files (x86)\Google\Application\chrome.exe" --user-data-dir="C:\Chrome_Data\OO7" --allow-file-access-from-files

Hope this helps anyone.

WordPress asking for my FTP credentials to install plugins

"Whenever you use the WordPress control panel to automatically install, upgrade, or delete plugins, WordPress must make changes to files on the filesystem.

Before making any changes, WordPress first checks to see whether or not it has access to directly manipulate the file system.

If WordPress does not have the necessary permissions to modify the filesystem directly, you will be asked for FTP credentials so that WordPress can try to do what it needs to via FTP."

Solution: In order to find out what user your instance of apache is running as, create a test script with the following content:

<?php echo(exec("whoami")); ?>

For me, it was daemon and not www-data. Then, fix the permission by:

sudo chown -R daemon /path/to/your/local/www/folder

Automatic HTTPS connection/redirect with node.js/express

You can use the express-force-https module:

npm install --save express-force-https

var express = require('express');
var secure = require('express-force-https');

var app = express();
app.use(secure);

Query error with ambiguous column name in SQL

Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.

ios app maximum memory budget

In my app, user experience is better if more memory is used, so I have to decide if I really should free all the memory I can in didReceiveMemoryWarning. Based on Split's and Jasper Pol's answer, using a maximum of 45% of the total device memory appears to be a safe threshold (thanks guys).

In case someone wants to look at my actual implementation:

#import "mach/mach.h"

- (void)didReceiveMemoryWarning
{
    // Remember to call super
    [super didReceiveMemoryWarning];

    // If we are using more than 45% of the memory, free even important resources,
    // because the app might be killed by the OS if we don't
    if ([self __getMemoryUsedPer1] > 0.45)
    {
        // Free important resources here
    }

    // Free regular unimportant resources always here
}

- (float)__getMemoryUsedPer1
{
    struct mach_task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
    if (kerr == KERN_SUCCESS)
    {
        float used_bytes = info.resident_size;
        float total_bytes = [NSProcessInfo processInfo].physicalMemory;
        //NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
        return used_bytes / total_bytes;
    }
    return 1;
}

Swift (based on this answer):

func __getMemoryUsedPer1() -> Float
{
    let MACH_TASK_BASIC_INFO_COUNT = (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))
    let name = mach_task_self_
    let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
    var size = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)
    var infoPointer = UnsafeMutablePointer<mach_task_basic_info>.alloc(1)
    let kerr = task_info(name, flavor, UnsafeMutablePointer(infoPointer), &size)
    let info = infoPointer.move()
    infoPointer.dealloc(1)
    if kerr == KERN_SUCCESS
    {
        var used_bytes: Float = Float(info.resident_size)
        var total_bytes: Float = Float(NSProcessInfo.processInfo().physicalMemory)
        println("Used: \(used_bytes / 1024.0 / 1024.0) MB out of \(total_bytes / 1024.0 / 1024.0) MB (\(used_bytes * 100.0 / total_bytes)%%)")
        return used_bytes / total_bytes
    }
    return 1
}

Is there a simple way to remove multiple spaces in a string?

foo is your string:

" ".join(foo.split())

Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n" will effectively end up as "this is a test".

How to insert newline in string literal?

If you are working with Web application you can try this.

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).

It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project

enter image description here

JavaScript: Object Rename Key

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

I wish the syntax wasn't this complex but it is definitely nice having more control.

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

Accessing members of items in a JSONArray with Java

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Oracle JDBC drivers and other companion Jars are available on Central Maven. We suggest to use the official supported Oracle JDBC versions from 11.2.0.4, 12.2.0.2, 18.3.0.0, 19.3.0.0, 19.6.0.0, and 19.7.0.0. These are available on Central Maven Repository. Refer to Maven Central Guide for more details.

It is recommended to use the latest version. Check out FAQ for JDK compatibility.

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

How to get year and month from a date - PHP

$dateValue = strtotime($q);

$yr = date("Y", $dateValue) ." "; 
$mon = date("m", $dateValue)." "; 
$date = date("d", $dateValue); 

Where is SQLite database stored on disk?

When you call sqlite3_open() you specify the filepath the database is opened from/saved to, if it is not an absolute path it is specified relative to your current working directory.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Cannot get OpenCV to compile because of undefined references?

if anyone still having this problem. One solution is to rebuild the source OpenCV library using MinGW and not use the binaries given by OpenCV. I did it and it worked like a charm.

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

Selenium and xpath: finding a div with a class/id and verifying text inside

To account for leading and trailing whitespace, you probably want to use normalize-space()

//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']

and

//div[@id='alertLabel' and normalize-space(.)='Save to server successful']

Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] also works.

In C#, what is the difference between public, private, protected, and having no access modifier?

A graphical overview (summary in a nutshell)

Visibility

Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.



For the defaults if you put no access modifier in front, see here:
Default visibility for C# classes and members (fields, methods, etc.)?

Non-nested

enum                              public
non-nested classes / structs      internal
interfaces                        internal
delegates in namespace            internal
class/struct member(s)            private
delegates nested in class/struct  private

Nested:

nested enum      public
nested interface public
nested class     private
nested struct    private

Also, there is the sealed-keyword, which makes a class not-inheritable.
Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:

VB vs. CS equivalents

Why am I seeing "TypeError: string indices must be integers"?

The variable item is a string. An index looks like this:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

The above example uses the 0 index of the string to refer to the first character.

Strings can't have string indices (like dictionaries can). So this won't work:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers

How to use target in location.href

The problem is that some versions of explorer don't support the window.open javascript function

Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.

Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.

There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".

How to get element by class name?

you can use

getElementsByClassName

suppose you have some elements and applied a class name 'test', so, you can get elements like as following

var tests = document.getElementsByClassName('test');

its returns an instance NodeList, or its superset: HTMLCollection (FF).

Read more

An existing connection was forcibly closed by the remote host

Had the same bug. Actually worked in case the traffic was sent using some proxy (fiddler in my case). Updated .NET framework from 4.5.2 to >=4.6 and now everything works fine. The actual request was:
new WebClient().DownloadData("URL");
The exception was:

SocketException: An existing connection was forcibly closed by the remote host

How to check a string for specific characters?

user Jochen Ritzel said this in a comment to an answer to this question from user dappawit. It should work:

('1' in var) and ('2' in var) and ('3' in var) ...

'1', '2', etc. should be replaced with the characters you are looking for.

See this page in the Python 2.7 documentation for some information on strings, including about using the in operator for substring tests.

Update: This does the same job as my above suggestion with less repetition:

# When looking for single characters, this checks for any of the characters...
# ...since strings are collections of characters
any(i in '<string>' for i in '123')
# any(i in 'a' for i in '123') -> False
# any(i in 'b3' for i in '123') -> True

# And when looking for subsrings
any(i in '<string>' for i in ('11','22','33'))
# any(i in 'hello' for i in ('18','36','613')) -> False
# any(i in '613 mitzvahs' for i in ('18','36','613')) ->True

How to do a newline in output

Use "\n" instead of '\n'

How do I keep the screen on in my App?

There are multiple ways you can do it:

Solution 1:

class MainActivity extends AppCompactActivity {
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);    
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Solution 2:

In activity_main.xml file, simply add:

<android:KeepScreenOn="true"/>

My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.

Also, make sure to turn off the screen while closing the activity. You can do it in this way:

public void onDestry() {
    getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Fastest method to escape HTML tags as HTML entities?

You could try passing a callback function to perform the replacement:

var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
};

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);
}

Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace function repeatedly, and using the DOM method proposed by Dmitrij.

Your way seems to be faster...

Why do you need it, though?

Best way to convert text files between character sets?

iconv(1)

iconv -f FROM-ENCODING -t TO-ENCODING file.txt

Also there are iconv-based tools in many languages.

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

Perhaps you want Hash#merge ?

1.9.3p194 :015 > h={}
 => {} 
1.9.3p194 :016 > h.merge(:key => 'bar')
 => {:key=>"bar"} 
1.9.3p194 :017 > 

If you want to change the array in place use merge!

1.9.3p194 :016 > h.merge!(:key => 'bar')
 => {:key=>"bar"} 

How can I check if a MySQL table exists with PHP?

// Select 1 from table_name will return false if the table does not exist.
$val = mysql_query('select 1 from `table_name` LIMIT 1');

if($val !== FALSE)
{
   //DO SOMETHING! IT EXISTS!
}
else
{
    //I can't find it...
}

Admittedly, it is more Pythonic than of the PHP idiom, but on the other hand, you don't have to worry about dealing with a copious amount of extra data.

Edit

So, this answer has been marked down at least twice as of the time I am writing this message. Assuming that I had made some gargantuan error, I went and I ran some benchmarks, and this is what I found that my solution is over 10% faster than the nearest alternative when the table does not exist, and it over 25% faster when the table does exist:

:::::::::::::::::::::::::BEGINNING NON-EXISTING TABLE::::::::::::::::::::::::::::::
23.35501408577 for bad select
25.408507823944 for select from schema num rows -- calls mysql_num_rows on select... from information_schema.
25.336688995361 for select from schema fetch row -- calls mysql_fetch_row on select... from information_schema result
50.669058799744 for SHOW TABLES FROM test
:::::::::::::::::::::::::BEGINNING EXISTING TABLE::::::::::::::::::::::::::::::
15.293519973755 for good select
20.784908056259 for select from schema num rows
21.038464069366 for select from schema fetch row
50.400309085846 for SHOW TABLES FROM test

I tried running this against DESC, but I had a timeout after 276 seconds (24 seconds for my answer, 276 to fail to complete the description of a non existing table).

For good measure, I am benchmarking against a schema with only four tables in it and this is an almost fresh MySQL install (this is the only database so far). To see the export, look here.

AND FURTHERMORE

This particular solution is also more database independent as the same query will work in PgSQL and Oracle.

FINALLY

mysql_query() returns FALSE for errors that aren't "this table doesn't exist".

If you need to guarantee that the table doesn't exist, use mysql_errno() to get the error code and compare it to the relevant MySQL errors.

Sharing a URL with a query string on Twitter

You don't necessarily need to use intent, it you encode your URL it will work with twitter share as well.

How to add 30 minutes to a JavaScript Date object?

var d1 = new Date (),
    d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );

Generating random whole numbers in JavaScript in a specific range?

For best performance, you can simply use:

var r = (Math.random() * (maximum - minimum + 1) ) << 0

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

React - Preventing Form Submission

componentDidUpdate(){               
    $(".wpcf7-submit").click( function(event) {
        event.preventDefault();
    })
}

You can use componentDidUpdate and event.preventDefault() to disable form submission.As react does not support return false.

How to get the previous url using PHP

Use the $_SERVER['HTTP_REFERER'] header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.

Best way to add Gradle support to IntelliJ Project

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

org.hibernate.MappingException: Could not determine type for: java.util.Set

My guess is you are using a Set<Role> in the User class annotated with @OneToMany. Which means one User has many Roles. But on the same field you use the @Column annotation which makes no sense. One-to-many relationships are managed using a separate join table or a join column on the many side, which in this case would be the Role class. Using @JoinColumn instead of @Column would probably fix the issue, but it seems semantically wrong. I guess the relationship between role and user should be many-to-many.

How to write a PHP ternary operator

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

Upload file to FTP using C#

I have observed that -

  1. FtpwebRequest is missing.
  2. As the target is FTP, so the NetworkCredential required.

I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :

private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
        {
            //Get the Image Destination path
            string imageName = TargetFileName; //you can comment this
            string imgPath = TargetDestinationPath; 

            string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
            string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
            string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
            string fileurl = FiletoUpload;

            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
            ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
            ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpClient.UseBinary = true;
            ftpClient.KeepAlive = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer = new byte[4097];
            int bytes = 0;
            int total_bytes = (int)fi.Length;
            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream rs = ftpClient.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            string value = uploadResponse.StatusDescription;
            uploadResponse.Close();
        }

Let me know in case of any issue, or here is one more link that can help you:

https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

Multiple select statements in Single query

SELECT  (
    SELECT COUNT(*)
    FROM   user_table
) AS tot_user,
(
    SELECT COUNT(*)
    FROM   cat_table
) AS tot_cat,
(
    SELECT COUNT(*)
    FROM   course_table
) AS tot_course

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

Check out this one:

https://github.com/VBA-tools/VBA-Web

It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.

How to make a Bootstrap accordion collapse when clicking the header div?

Simple solution would be to remove padding from .panel-heading and add to .panel-title a.

.panel-heading {
    padding: 0;
}
.panel-title a {
    display: block;
    padding: 10px 15px;
}

This solution is similar to the above one posted by calfzhou, slightly different.

Statistics: combinations in Python

That's probably as fast as you can do it in pure python for reasonably large inputs:

def choose(n, k):
    if k == n: return 1
    if k > n: return 0
    d, q = max(k, n-k), min(k, n-k)
    num =  1
    for n in xrange(d+1, n+1): num *= n
    denom = 1
    for d in xrange(1, q+1): denom *= d
    return num / denom

Event binding on dynamically created elements?

Another flexible solution to create elements and bind events (source)

// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);

Note: This will create an event handler instance for each element (may affect performance when used in loops)

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:

/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar

If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

What does "subject" mean in certificate?

My typical expectation is than when "subject" is used a context like this, it means the target of the certificate. If you think of a certificate as a cryptographically secured description of a thing (person, device, communication channel, etc), then the subject is the stuff related to that thing.

It's not the thing itself. For example, no one would say "the subject takes his SmartCard and authenticates his PIN". That would be the "user".

But it usually relates to the various data items related to that that thing. For example:

  • Subject DN = Subject Distinguished Name = the unique identifier for what this thing is. Includes information about the thing being certified, including common name, organization, organization unit, country codes, etc.
  • Subject Key = part (or all) of the certificate's private/public key pair. If it's coming from the certificate, it's the public key. If it's coming from a key store in a secure location, it's probably the private key. Either part of the key is the cryptographic data used by the thing that received the certificate.
  • Subject certificate - the end point for the transaction - this is the thing requesting some secure capability - like integrity checking, authentication, privacy, etc.

Usually, it's used to distinguish between the other players in the PKI world. Namely the "issuer" and the "root". The issuer is the CA that issued the cert (to the subject), and the root is the CA that is end point of all the trust in the heirarchy. The typical relationship is root--->issuer--->subject.

git: fatal: I don't handle protocol '??http'

The solution is very simple:

1- Copy your git path. forexample : http://github.com/yourname/my-git-project.git

2- Open notepad and Paste it. Then copy the path from notepad.

3- paste the path to command line

thats it.

How to change the interval time on bootstrap carousel?

        You need to set interval in  main div as data-interval tag .
        so it is working fine and you can give different time to different slides.

       <!--main div -->
      <div data-ride="carousel" class="carousel slide" data-interval="100" id="carousel-example-generic">
  <!-- Indicators -->
  <ol class="carousel-indicators">
                                <li data-target="#carousel-example-generic" data-slide-to="0" class=""></li>
                             i>
                                            </ol>

  <!-- Wrapper for slides -->
  <div role="listbox" class="carousel-inner">
       <div class="item">
          <a class="carousel-image" href="#">
           <img alt="image" src="image.jpg">
          </a>
        </div>
    </div>
 </div>

if statements matching multiple values

Is this what you are looking for ?

if (new int[] { 1, 2, 3, 4, 5 }.Contains(value))

bundle install returns "Could not locate Gemfile"

You must be in the same directory of Gemfile

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

Execute Insert command and return inserted Id in Sql

The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this

FOR SQL SERVER 2005 and above

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified =(int)cmd.ExecuteScalar();

        if (con.State == System.Data.ConnectionState.Open) 
            con.Close();

        return modified;
    }
}

FOR previous versions

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ)  VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified = Convert.ToInt32(cmd.ExecuteScalar());

        if (con.State == System.Data.ConnectionState.Open) con.Close();
            return modified;
    }
}

What Process is using all of my disk IO

atop also works well and installs easily even on older CentOS 5.x systems which can't run iotop. Hit d to show disk details, ? for help.

ATOP - mybox                           2014/09/08  15:26:00                           ------                            10s elapsed
PRC |  sys    0.33s |  user   1.08s |                | #proc    161  |  #zombie    0 |  clones    31 |                | #exit         16  |
CPU |  sys   4% |  user     11% |  irq       0%  | idle    306%  |  wait     79% |               |  steal     1%  | guest     0%  |
cpu |  sys   2% |  user      8% |  irq       0%  | idle     11%  |  cpu000 w 78% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     98%  |  cpu001 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     99%  |  cpu003 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   0% |  user      1% |  irq       0%  | idle     99%  |  cpu002 w  0% |               |  steal     0%  | guest     0%  |
CPL |  avg1    2.09 |  avg5    2.09 |  avg15   2.09  |               |  csw    54184 |  intr   33581 |                | numcpu     4  |
MEM |  tot     8.0G |  free   81.9M |  cache   2.9G  | dirty   0.8M  |  buff  174.7M |  slab  305.0M |                |               |
SWP |  tot     2.0G |  free    2.0G |                |               |               |               |  vmcom   8.4G  | vmlim   6.0G  |
LVM |  Group00-root |  busy     85% |  read       0  | write  30658  |  KiB/w      4 |  MBr/s   0.00 |  MBw/s  11.98  | avio 0.28 ms  |
DSK |          xvdb |  busy     85% |  read       0  | write  23706  |  KiB/w      5 |  MBr/s   0.00 |  MBw/s  11.97  | avio 0.36 ms  |
NET |  transport    |  tcpi    2705 |  tcpo    2008  | udpi      36  |  udpo      43 |  tcpao     14 |  tcppo     45  | tcprs      1  |
NET |  network      |  ipi     2788 |  ipo     2072  | ipfrw      0  |  deliv   2768 |               |  icmpi      7  | icmpo     20  |
NET |  eth0    ---- |  pcki    2344 |  pcko    1623  | si 1455 Kbps  |  so  781 Kbps |  erri       0 |  erro       0  | drpo       0  |
NET |  lo      ---- |  pcki     423 |  pcko     423  | si   88 Kbps  |  so   88 Kbps |  erri           0 |  erro       0  | drpo       0  |
NET |  eth1    ---- |  pcki  22 |  pcko      26  | si    3 Kbps  |  so    5 Kbps |  erri       0 |  erro       0  | drpo       0  |

  PID                   RDDSK                    WRDSK                   WCANCL                    DSK                   CMD        1/1
 9862                      0K                   53124K                       0K                    98%                   java
  358                      0K                     636K                       0K                     1%                   jbd2/dm-0-8
13893                      0K                     192K                      72K                     0%                   java
 1699                      0K                      60K                       0K                     0%                   syslogd
 4668                      0K                      24K                       0K                     0%                   zabbix_agentd

This clearly shows java pid 9862 is the culprit.

PHPMailer: SMTP Error: Could not connect to SMTP host

Your problem is most likely this

Connection Security: STARTTLS Connection Security: SSL/TLS

Those are 2 different protocols, are you using the correct one, whatever one you're using in Thunderbird needs to be used.

Try setting the variable:

// if you're using SSL
$mail->SMTPSecure = 'ssl';
// OR use TLS
$mail->SMTPSecure = 'tls';

How to use GNU Make on Windows?

While make itself is available as a standalone executable (gnuwin32.sourceforge.net package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Just in case of someone has the same problem. I'am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8", the problem is gone.

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

For me following worked:

in directive declare it like this:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            myFunction: '=',
        },
        templateUrl: 'myDirective.html'
    };
})  

In directive template use it in following way:

<select ng-change="myFunction(selectedAmount)">

And then when you use the directive, pass the function like this:

<data-my-directive
    data-my-function="setSelectedAmount">
</data-my-directive>

You pass the function by its declaration and it is called from directive and parameters are populated.

C# delete a folder and all files and folders within that folder

The Directory.Delete method has a recursive boolean parameter, it should do what you need

Call multiple functions onClick ReactJS

Maybe you can use arrow function (ES6+) or the simple old function declaration.

Normal function declaration type (Not ES6+):

<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>

Anonymous function or arrow function type (ES6+)

<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>

The second one is the shortest road that I know. Hope it helps you!

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

How do I see the extensions loaded by PHP?

If you want to test if a particular extension is loaded you can also use the extension_loaded function, see documentation here

php -r "var_dump(extension_loaded('json'));"

Android Open External Storage directory(sdcard) for storing file

I want to open external storage directory path for saving file programatically.I tried but not getting sdcard path. How can i do this?is there any solution for this??

To store your app files in SD card, you should use File[] getExternalFilesDirs (String type) method in Context class. Generally, second returned path would be the storage path for microSD card (if any).

On my phone, second path returned was /storage/sdcard1/Android/data/your.application.package.appname/files after passing null as argument to getExternalFilesDirs (String type). But path may vary on different phones, different Android versions.

Both File getExternalStorageDirectory () and File getExternalStoragePublicDirectory (String type) in Environment class may return SD card directory or internal memory directory depending on your phone's model and Android OS version.

Because According to Official Android Guide external storage can be

removable storage media (such as an SD card) or an internal (non-removable) storage.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

How to center the text in PHPExcel merged cell

if you want to align only this cells, you can do something like this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getStyle("A1:B1")->applyFromArray($style);

But, if you want to apply this style to all cells, try this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getDefaultStyle()->applyFromArray($style);

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

How do I compare two strings in python?

Try to covert both strings to upper or lower case. Then you can use == comparison operator.

How do I enable EF migrations for multiple contexts to separate databases?

EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.

More than one context type was found in the assembly 'Service.Domain'.

To enable migrations for 'Service.Domain.DatabaseContext.Context1', 
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.

How to return a value from try, catch, and finally?

The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

How to run a script as root on Mac OS X?

sudo ./scriptname

sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.

How to pass a variable to the SelectCommand of a SqlDataSource?

try with this.

Protected Sub SqlDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource.Selecting

    e.Command.CommandText = "SELECT [ImageID],[ImagePath] FROM [TblImage] where IsActive = 1"

    End Sub

How do I check whether an array contains a string in TypeScript?

You can use filter too

this.products = array_products.filter((x) => x.Name.includes("ABC"))

Getting SyntaxError for print with keyword argument end=' '

Try this one if you are working with python 2.7:

from __future__ import print_function

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

keycode 13 is for which key

_x000D_
_x000D_
function myFunction(event) {
  var x = event.charCode;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
}
_x000D_
<p>Keycode 13 is: </p> 
<button>Enter</button>
<p>Press a key on the keyboard in the input field to get the Unicode character code of the pressed key.</p>
<b>You can test in below</b>

<input type="text" size="40" onkeypress="myFunction(event)">

<p id="demo"></p>

<p><strong>Note:</strong> The charCode property is not supported in IE8 and earlier versions.</p>
_x000D_
_x000D_
_x000D_

Handling JSON Post Request in Go

You need to read from req.Body. The ParseForm method is reading from the req.Body and then parsing it in standard HTTP encoded format. What you want is to read the body and parse it in JSON format.

Here's your code updated.

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "io/ioutil"
)

type test_struct struct {
    Test string
}

func test(rw http.ResponseWriter, req *http.Request) {
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic(err)
    }
    log.Println(string(body))
    var t test_struct
    err = json.Unmarshal(body, &t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

func main() {
    http.HandleFunc("/test", test)
    log.Fatal(http.ListenAndServe(":8082", nil))
}

How do I prevent mails sent through PHP mail() from going to spam?

<?php 
$to1 = '[email protected]';
$subject = 'Tester subject'; 

    // To send HTML mail, the Content-type header must be set

    $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
    $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
    $headers .= "From: [email protected]" ."\r\n" .
    $headers .= "Organization: Sender Organization\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>

Center Align on a Absolutely Positioned Div

_x000D_
_x000D_
.contentBlock {_x000D_
    width: {define width}_x000D_
    width: 400px;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
 _x000D_
}
_x000D_
_x000D_
_x000D_

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Python logging: use milliseconds in time format

If you prefer to use style='{', fmt="{asctime}.{msecs:0<3.0f}" will 0-pad your microseconds to three places for consistency.