Programs & Examples On #Smartpart

How to subtract 30 days from the current datetime in mysql?

Let's not use NOW() as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.

In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.

Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW() function as it kills your caching.

SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);

You can use BETWEEN if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.

What are the differences between the urllib, urllib2, urllib3 and requests module?

I think all answers are pretty good. But fewer details about urllib3.urllib3 is a very powerful HTTP client for python. For installing both of the following commands will work,

urllib3

using pip,

pip install urllib3

or you can get the latest code from Github and install them using,

$ git clone git://github.com/urllib3/urllib3.git
$ cd urllib3
$ python setup.py install

Then you are ready to go,

Just import urllib3 using,

import urllib3

In here, Instead of creating a connection directly, You’ll need a PoolManager instance to make requests. This handles connection pooling and thread-safety for you. There is also a ProxyManager object for routing requests through an HTTP/HTTPS proxy Here you can refer to the documentation. example usage :

>>> from urllib3 import PoolManager
>>> manager = PoolManager(10)
>>> r = manager.request('GET', 'http://google.com/')
>>> r.headers['server']
'gws'
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> r.headers['server']
'YTS/1.20.0'
>>> r = manager.request('POST', 'http://google.com/mail')
>>> r = manager.request('HEAD', 'http://google.com/calendar')
>>> len(manager.pools)
2
>>> conn = manager.connection_from_host('google.com')
>>> conn.num_requests
3

As mentioned in urrlib3 documentations,urllib3 brings many critical features that are missing from the Python standard libraries.

  • Thread safety.
  • Connection pooling.
  • Client-side SSL/TLS verification.
  • File uploads with multipart encoding.
  • Helpers for retrying requests and dealing with HTTP redirects.
  • Support for gzip and deflate encoding.
  • Proxy support for HTTP and SOCKS.
  • 100% test coverage.

Follow the user guide for more details.

requests

requests uses urllib3 under the hood and make it even simpler to make requests and retrieve data. For one thing, keep-alive is 100% automatic, compared to urllib3 where it's not. It also has event hooks which call a callback function when an event is triggered, like receiving a response In requests, each request type has its own function. So instead of creating a connection or a pool, you directly GET a URL.


For install requests using pip just run

pip install requests

or you can just install from source code,

$ git clone git://github.com/psf/requests.git
$ cd requests
$ python setup.py install

Then, import requests

Here you can refer the official documentation, For some advanced usage like session object, SSL verification, and Event Hooks please refer to this url.

How to make div appear in front of another?

Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Bootstrap - dropdown menu not working?

Check if you're referencing jquery.js BEFORE bootstrap.js and bootstrap.js is loaded only once. That fixed the same error for me:

<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>

How to set column widths to a jQuery datatable?

by using css we can easily add width to the column.

here im adding first column width to 300px on header (thead)

_x000D_
_x000D_
::ng-deep  table thead tr:last-child th:nth-child(1) {_x000D_
    width: 300px!important;_x000D_
}
_x000D_
_x000D_
_x000D_

now add same width to tbody first column by,

_x000D_
_x000D_
  <table datatable class="display table ">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th class="text-left" style="width: 300px!important;">name</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
           _x000D_
            <tr>_x000D_
                <td class="text-left" style="width: 300px!important;">jhon mathew</td>_x000D_
                _x000D_
            </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
       
_x000D_
_x000D_
_x000D_

by this way you can easily change width by changing the order of nth child. if you want 3 column then ,add nth-child(3)

What are Maven goals and phases and what is their difference?

Life cycle is a sequence of named phases.
Phases executes sequentially. Executing a phase means executes all previous phases.

Plugin is a collection of goals also called MOJO (Maven Old Java Object).
Analogy : Plugin is a class and goals are methods within the class.

Maven is based around the central concept of a Build Life Cycles. Inside each Build Life Cycles there are Build Phases, and inside each Build Phases there are Build Goals.

We can execute either a build phase or build goal. When executing a build phase we execute all build goals within that build phase. Build goals are assigned to one or more build phases. We can also execute a build goal directly.

There are three major built-in Build Life Cycles:

  1. default
  2. clean
  3. site

Each Build Lifecycle is Made Up of Phases

For example the default lifecycle comprises of the following Build Phases:

?validate - validate the project is correct and all necessary information is available
?compile - compile the source code of the project
?test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
?package - take the compiled code and package it in its distributable format, such as a JAR.
?integration-test - process and deploy the package if necessary into an environment where integration tests can be run
?verify - run any checks to verify the package is valid and meets quality criteria
?install - install the package into the local repository, for use as a dependency in other projects locally
?deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

So to go through the above phases, we just have to call one command:

mvn <phase> { Ex: mvn install }

For the above command, starting from the first phase, all the phases are executed sequentially till the ‘install’ phase. mvn can either execute a goal or a phase (or even multiple goals or multiple phases) as follows:

mvn clean install plugin:goal  

However, if you want to customize the prefix used to reference your plugin, you can specify the prefix directly through a configuration parameter on the maven-plugin-plugin in your plugin's POM.

A Build Phase is Made Up of Plugin Goals

Most of Maven's functionality is in plugins. A plugin provides a set of goals that can be executed using the following syntax:

 mvn [plugin-name]:[goal-name]

For example, a Java project can be compiled with the compiler-plugin's compile-goal by running mvn compiler:compile.

Build lifecycle is a list of named phases that can be used to give order to goal execution.

Goals provided by plugins can be associated with different phases of the lifecycle. For example, by default, the goal compiler:compile is associated with the compile phase, while the goal surefire:test is associated with the test phase. Consider the following command:

mvn test

When the preceding command is executed, Maven runs all goals associated with each of the phases up to and including the test phase. In such a case, Maven runs the resources:resources goal associated with the process-resources phase, then compiler:compile, and so on until it finally runs the surefire:test goal.

However, even though a build phase is responsible for a specific step in the build lifecycle, the manner in which it carries out those responsibilities may vary. And this is done by declaring the plugin goals bound to those build phases.

A plugin goal represents a specific task (finer than a build phase) which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation. The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases, while the dependency:copy-dependencies is a goal (of a plugin).

mvn clean dependency:copy-dependencies package

If this were to be executed, the clean phase will be executed first (meaning it will run all preceding phases of the clean lifecycle, plus the clean phase itself), and then the dependency:copy-dependencies goal, before finally executing the package phase (and all its preceding build phases of the default lifecycle).

Moreover, if a goal is bound to one or more build phases, that goal will be called in all those phases.

Furthermore, a build phase can also have zero or more goals bound to it. If a build phase has no goals bound to it, that build phase will not execute. But if it has one or more goals bound to it, it will execute all those goals.

Built-in Lifecycle Bindings
Some phases have goals bound to them by default. And for the default lifecycle, these bindings depend on the packaging value.

Maven Architecture:

enter image description here

Reference 1
Reference 2

Eclipse sample for Maven Lifecycle Mapping

Eclipse sample for Maven Lifecycle Mapping

How can I permanently enable line numbers in IntelliJ?

IntelliJ 14.X Onwards

From version 14.0 onwards, the path to the setting dialog is slightly different, a General submenu has been added between Editor and Appearance as shown below

enter image description here

IntelliJ 8.1.2 - 13.X

From IntelliJ 8.1.2 onwards, this option is in File | Settings1. Within the IDE Settings section of that dialog, you'll find it under Editor | Appearance.

  1. On a Mac, these are named IntelliJ IDEA | Preferences...

enter image description here

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Bear in mind that the GoogleFinance() function isn't working 100% in the new version of Google Sheets. For example, converting from USD to GBP using the formula GoogleFinance("CURRENCY:USDGBP") gives 0.603974 in the old version, but only 0.6 in the new one. Looks like there's a rounding error.

When is std::weak_ptr useful?

I see std::weak_ptr<T> as a handle to a std::shared_ptr<T>: It allows me to get the std::shared_ptr<T> if it still exists, but it will not extend its lifetime. There are several scenarios when such point of view is useful:

// Some sort of image; very expensive to create.
std::shared_ptr< Texture > texture;

// A Widget should be able to quickly get a handle to a Texture. On the
// other hand, I don't want to keep Textures around just because a widget
// may need it.

struct Widget {
    std::weak_ptr< Texture > texture_handle;
    void render() {
        if (auto texture = texture_handle.get(); texture) {
            // do stuff with texture. Warning: `texture`
            // is now extending the lifetime because it
            // is a std::shared_ptr< Texture >.
        } else {
            // gracefully degrade; there's no texture.
        }
    }
};

Another important scenario is to break cycles in data structures.

// Asking for trouble because a node owns the next node, and the next node owns
// the previous node: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > next;
    std::shared_ptr< Node > prev;
};

// Asking for trouble because a parent owns its children and children own their
// parents: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::shared_ptr< Node > next;
    std::weak_ptr< Node > prev;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::weak_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

Herb Sutter has an excellent talk that explains the best use of language features (in this case smart pointers) to ensure Leak Freedom by Default (meaning: everything clicks in place by construction; you can hardly screw it up). It is a must watch.

Wait Until File Is Completely Written

So, having glanced quickly through some of these and other similar questions I went on a merry goose chase this afternoon trying to solve a problem with two separate programs using a file as a synchronization (and also file save) method. A bit of an unusual situation, but it definitely highlighted for me the problems with the 'check if the file is locked, then open it if it's not' approach.

The problem is this: the file can become locked between the time that you check it and the time you actually open the file. Its really hard to track down the sporadic Cannot copy the file, because it's used by another process error if you aren't looking for it too.

The basic resolution is to just try to open the file inside a catch block so that if its locked, you can try again. That way there is no elapsed time between the check and the opening, the OS does them at the same time.

The code here uses File.Copy, but it works just as well with any of the static methods of the File class: File.Open, File.ReadAllText, File.WriteAllText, etc.

/// <param name="timeout">how long to keep trying in milliseconds</param>
static void safeCopy(string src, string dst, int timeout)
{
    while (timeout > 0)
    {
        try
        {
            File.Copy(src, dst);

            //don't forget to either return from the function or break out fo the while loop
            break;
        }
        catch (IOException)
        {
            //you could do the sleep in here, but its probably a good idea to exit the error handler as soon as possible
        }
        Thread.Sleep(100);

        //if its a very long wait this will acumulate very small errors. 
        //For most things it's probably fine, but if you need precision over a long time span, consider
        //   using some sort of timer or DateTime.Now as a better alternative
        timeout -= 100;
    }
}

Another small note on parellelism: This is a synchronous method, which will block its thread both while waiting and while working on the thread. This is the simplest approach, but if the file remains locked for a long time your program may become unresponsive. Parellelism is too big a topic to go into in depth here, (and the number of ways you could set up asynchronous read/write is kind of preposterous) but here is one way it could be parellelized.

public class FileEx
{
    public static async void CopyWaitAsync(string src, string dst, int timeout, Action doWhenDone)
    {
        while (timeout > 0)
        {
            try
            {
                File.Copy(src, dst);
                doWhenDone();
                break;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }

    public static async Task<string> ReadAllTextWaitAsync(string filePath, int timeout)
    {
        while (timeout > 0)
        {
            try {
                return File.ReadAllText(filePath);
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
        return "";
    }

    public static async void WriteAllTextWaitAsync(string filePath, string contents, int timeout)
    {
        while (timeout > 0)
        {
            try
            {
                File.WriteAllText(filePath, contents);
                return;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }
}

And here is how it could be used:

public static void Main()
{
    test_FileEx();
    Console.WriteLine("Me First!");
}    

public static async void test_FileEx()
{
    await Task.Delay(1);

    //you can do this, but it gives a compiler warning because it can potentially return immediately without finishing the copy
    //As a side note, if the file is not locked this will not return until the copy operation completes. Async functions run synchronously
    //until the first 'await'. See the documentation for async: https://msdn.microsoft.com/en-us/library/hh156513.aspx
    CopyWaitAsync("file1.txt", "file1.bat", 1000);

    //this is the normal way of using this kind of async function. Execution of the following lines will always occur AFTER the copy finishes
    await CopyWaitAsync("file1.txt", "file1.readme", 1000);
    Console.WriteLine("file1.txt copied to file1.readme");

    //The following line doesn't cause a compiler error, but it doesn't make any sense either.
    ReadAllTextWaitAsync("file1.readme", 1000);

    //To get the return value of the function, you have to use this function with the await keyword
    string text = await ReadAllTextWaitAsync("file1.readme", 1000);
    Console.WriteLine("file1.readme says: " + text);
}

//Output:
//Me First!
//file1.txt copied to file1.readme
//file1.readme says: Text to be duplicated!

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

How can I jump to class/method definition in Atom text editor?

For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-

https://atom.io/packages/atom-typescript#alternative-to-symbols-view

Pandas get the most frequent values of a column

To get the n most frequent values, just subset .value_counts() and grab the index:

# get top 10 most frequent names
n = 10
dataframe['name'].value_counts()[:n].index.tolist()

How do I install Python 3 on an AWS EC2 instance?

If you do a

sudo yum list | grep python3

you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:

sudo yum install python34 python34-pip

Incrementing a date in JavaScript

Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON Slice the date from the returned value and then increment by the number of days you want.

var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);

how to reset <input type = "file">

You should try this:

$("#uploadCaptureInputFile").val('');

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

javascript regular expression to not match a word

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.

Javascript Array.sort implementation?

I think that would depend on what browser implementation you are refering to.

Every browser type has it's own javascript engine implementation, so it depends. You could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations.

IE is closed source however, so you may have to ask somebody at microsoft.

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Python String and Integer concatenation

for i in range (1,10):
    string="string"+str(i)

To get string0, string1 ..... string10, you could do like

>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

Calculate date from week number

this is my solution when we want to calculate a date given year, week number and day of the week.

int Year = 2014;
int Week = 48;
int DayOfWeek = 4;

DateTime FecIni = new DateTime(Year, 1, 1);
FecIni = FecIni.AddDays(7 * (Week - 1));
if ((int)FecIni.DayOfWeek > DayOfWeek)
{
    while ((int)FecIni.DayOfWeek != DayOfWeek) FecIni = FecIni.AddDays(-1);
}
else
{
    while ((int)FecIni.DayOfWeek != DayOfWeek) FecIni = FecIni.AddDays(1);
}

What is the purpose of the single underscore "_" variable in Python?

There are 5 cases for using the underscore in Python.

  1. For storing the value of last expression in interpreter.

  2. For ignoring the specific values. (so-called “I don’t care”)

  3. To give special meanings and functions to name of variables or functions.

  4. To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.

  5. To separate the digits of number literal value.

Here is a nice article with examples by mingrammer.

Why can't I define a static method in a Java interface?

Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.

With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.

How to create an array of 20 random bytes?

Create a Random object with a seed and get the array random by doing:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

JavaScript, getting value of a td with id name

For input you must have used value to grab its text but for td, you should use innerHTML to get its html/value. Example:

alert(document.getElementById("td_id_here").innerHTML);

To get its text though, use:

alert(document.getElementById("td_id_here").innerText);

Call another rest api from my server in Spring-Boot

This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

How can I get the console logs from the iOS Simulator?

In Xcode: View->Debug Area->Activate Console

enter image description here

Laravel Eloquent compare date from datetime field

You can get the all record of the date '2016-07-14' by using it

 whereDate('date','=','2016-07-14')

Or use the another code for dynamic date

whereDate('date',$date)

PHP mail not working for some reason

I'm using this for a while now, don't know if this is still up to date with the actual PHP versions. You can use this in a one file setup, or just split it up in two files like contact.php and index.php

contact.php | Code

<?php 
error_reporting(E_ALL ^ E_NOTICE); 


if(isset($_POST['submitted'])) {


if(trim($_POST['contactName']) === '') {
    $nameError =  '<span style="margin-left:40px;">You have missed your name.</span>'; 
    $hasError = true;
} else {
    $name = trim($_POST['contactName']);
}

if(trim($_POST['topic']) === '') {
    $topicError = '<span style="margin-left:40px;">You have missed the topic.</span>'; 
    $hasError = true;
} else {
    $topic = trim($_POST['topic']);
}

$telefon = trim($_POST['phone']);
$company = trim($_POST['company']);


if(trim($_POST['email']) === '')  {
    $emailError = '<span style="margin-left:40px;">You have missed your email adress.</span>';
    $hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
    $emailError = '<span style="margin-left:40px;">You have missspelled your email adress.</span>';
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}


if(trim($_POST['comments']) === '') {
    $commentError = '<span style="margin-left:40px;">You have missed the comment section.</span>';
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = utf8_encode(stripslashes(trim($_POST['comments'])));
    } else {
        $comments = trim($_POST['comments']);
    }
}


if(!isset($hasError)) {

    $emailTo = '[email protected]';
    $subject = 'Example.com - '.$name.' - '.$betreff;
    $sendCopy = trim($_POST['sendCopy']);
    $body = "\n\n This is an email from http://www.example.com \n\nCompany : $company\n\nName : $name \n\nEmail-Adress : $email \n\nPhone-No.. : $phone \n\nTopic : $topic\n\nMessage of the sender: $comments\n\n";
    $headers = "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n";

    mail($emailTo, $subject, $body, $headers);



    $emailSent = true;
}
}
?>

STYLESHEET

}
.formblock{display:block;padding:5px;margin:8px; margin-left:40px;}
.text{width:500px;height:200px;padding:5px;margin-left:40px;}
.center{min-height:12em;display:table-cell;vertical-align:middle;}
.failed{ margin-left:20px;font-size:18px;color:#C00;}
.okay{margin-left:20px;font-size:18px;color:#090;}
.alert{border:2px #fc0;padding:8px;text-transform:uppercase;font-weight:bold;}
.error{font-size:14px;color:#C00;}

label
{
margin-left:40px;
}

textarea

{
margin-left:40px;
}

index.php | FORM CODE

<?php header('Content-Type: text/html;charset=UTF-8'); ?>
<!DOCTYPE html>
<html lang="de">
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>


<form action="contact.php" method="post">

<?php if(isset($emailSent) && $emailSent == true) { ?>

<span class="okay">Thank you for your interest. Your email has been send !</span>

<br>

<br>

<?php } else { ?>

<?php if(isset($hasError) || isset($captchaError) ) { ?>

<span class="failed">Email not been send. Please check the contact form.</span>

<br>

<br>

<?php } ?>

<label class="text label">Company</label>

<br>

<input type="text" size="30" name="company" id="company" value="<?php if(isset($_POST['company'])) echo $_POST['comnpany'];?>" class="formblock" placeholder="Your Company">

<label class="text label">Your Name <strong class="error">*</strong></label>

<br>

<?php if($nameError != '') { ?>

<span class="error"><?php echo $nameError;?></span>

<?php } ?>

<input type="text" size="30" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="formblock" placeholder="Your Name">

<label class="text label">- Betreff - Anliegen - <strong class="error">*</strong></label>

<br>

<?php if($topicError != '') { ?>

<span class="error"><?php echo $betrError;?></span>

<?php } ?>

<input type="text" size="30" name="topic" id="topic" value="<?php if(isset($_POST['topic'])) echo $_POST['topic'];?>" class="formblock" placeholder="Your Topic">

<label class="text label">Phone-No.</label>

<br>

<input type="text" size="30" name="phone" id="phone" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>" class="formblock" placeholder="12345 678910">

<label class="text label">Email-Adress<strong class="error">*</strong></label>

<br>

<?php if($emailError != '') { ?>

<span class="error"><?php echo $emailError;?></span>

<?php } ?>

<input type="text" size="30" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="formblock" placeholder="[email protected]">

<label class="text label">Your Message<strong class="error">*</strong></label>

<br>

<?php if($commentError != '') { ?>

<span class="error"><?php echo $commentError;?></span>

<?php } ?>

<textarea name="comments" id="commentsText" class="formblock text" placeholder="Leave your message here..."><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>

<button class="formblock" name="submit" type="submit">Send Email</button>
<input type="hidden" name="submitted" id="submitted" value="true">
<?php } ?>

</form>
</body>
</html>

JAVASCRIPT

<script type="text/javascript">

<!--//--><![CDATA[//><!--

$(document).ready(function() {

$('form#contact-us').submit(function() {

$('form#contact-us .error').remove();
var hasError = false;

$('.requiredField').each(function() {

if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have missed '+labelText+'.</span>.');

$(this).addClass('inputError');
hasError = true;

} else if($(this).hasClass('email')) {

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {

var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have entered a wrong '+labelText+' adress.</span>.');

$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {

var formInput = $(this).serialize();

$.post($(this).attr('action'),formInput, function(data){

$('form#contact-us').slideUp("fast", function() {                  
$(this).before('<br><br><strong>Thank You!</strong>Your Email has been send successfuly.');

});

});

}
return false;   

});

});

//-->!]]>

</script>

How to Deserialize JSON data?

You can write your own JSON parser and make it more generic based on your requirement. Here is one which served my purpose nicely, hope will help you too.

class JsonParsor
{
    public static DataTable JsonParse(String rawJson)
    {
        DataTable dataTable = new DataTable();
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawJson);
        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        bool reading_number = false;
        while (s >= 0)
        {
            s = bufferreader.Read();
            //open JSON
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading)
                {
                    reading = true;
                    continue;
                }
                if ((char)s == '}' && !inside_string && !reading)
                    break;
                if ((char)s == ']' && !inside_string && !reading)
                    continue;
                if ((char)s == ',')
                    continue;
            }
            else
            {
                if (reading_value)
                {
                    if (!inside_string && (char)s >= '0' && (char)s <= '9')
                    {
                        reading_number = true;
                        valuebufferbuilder.Append((char)s);
                        continue;
                    }
                }
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    if ((char)s == '\"' && !inside_string)
                        inside_string = true;
                    if ((char)s == '[' && !inside_string)
                    {
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                                reading = false;
                                inside_string = false;
                                reading_value = false;
                    }
                    if ((char)s == ',' && !inside_string && reading_number)
                    {
                        if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                            dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                        if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                        reading_value = false;
                        reading_number = false;
                    }
                    continue;
                }

                //if we reach end of the string
                if (inside_string)
                {
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read();
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //put the key-value pair into dictionary
                            if(!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(),typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            keybufferbuilder.Length = 0;
                            valuebufferbuilder.Length = 0;
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            ICollection key = outdict.Keys;
                            DataRow newrow = dataTable.NewRow();
                            foreach (string k_loopVariable in key)
                            {
                                CommonModule.LogTheMessage(outdict[k_loopVariable],"","","");
                                newrow[k_loopVariable] = outdict[k_loopVariable];
                            }
                            dataTable.Rows.Add(newrow);
                            CommonModule.LogTheMessage(dataTable.Rows.Count.ToString(), "", "row_count", "");
                            outdict.Clear();
                            keybufferbuilder.Length=0;
                            valuebufferbuilder.Length=0;
                            reading_value = false;
                            reading = false;
                            continue;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }

        return dataTable;
    }
}

Select Pandas rows based on list index

Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:

df[df.index.isin([1,3])]

PS: You figure out the reason

enter image description here

How to style the parent element when hovering a child element?

This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

How should I have explained the difference between an Interface and an Abstract class?

Nothing is perfect in this world. They may have been expecting more of a practical approach.

But after your explanation you could add these lines with a slightly different approach.

  1. Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules) which works as a common understanding document among various teams in software development.

  2. Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules (means given signature of methods).

  3. Abstract classes may contain abstract declarations, concrete implementations, or both.

  4. Abstract declarations are like rules to be followed and concrete implementations are like guidelines (you can use it as it is or you can ignore it by overriding and giving your own implementation to it).

  5. Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

Edit: Java 8 facilitates to define default and static methods in interface.

public interface SomeInterfaceOne {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceOne defaultMethod::"+inputString);
    }
}

Now when a class will implement SomeInterface, it is not mandatory to provide implementation for default methods of interface.

If we have another interface with following methods:

public interface SomeInterfaceTwo {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceTwo defaultMethod::"+inputString);
    }

}

Java doesn’t allow extending multiple classes because it results in the “Diamond Problem” where compiler is not able to decide which superclass method to use. With the default methods, the diamond problem will arise for interfaces too. Because if a class is implementing both

SomeInterfaceOne and SomeInterfaceTwo

and doesn’t implement the common default method, compiler can’t decide which one to chose. To avoid this problem, in java 8 it is mandatory to implement common default methods of different interfaces. If any class is implementing both the above interfaces, it has to provide implementation for defaultMethod() method otherwise compiler will throw compile time error.

How to remove a branch locally?

As far I can understand the original problem, you added commits to local master by mistake and did not push that changes yet. Now you want to cancel your changes and hope to delete your local changes and to create a new master branch from the remote one.

You can just reset your changes and reload master from remote server:

git reset --hard origin/master

What does the following Oracle error mean: invalid column index

the final sql statement is something like:

select col_1 from table_X where col_2 = 'abcd';

i run this inside my SQL IDE and everything is ok.

Next, i try to build this statement with java:

String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index

Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.

i just removed the characters that appear on white background

"select col_1 from table_X where col_2 = ' ? ' ; ";

to obtain

"select col_1 from table_X where col_2 = ?";

(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)

Laravel form html with PUT method for PUT routes

Is very easy, you just need to use method_field('PUT') like this:

HTML:

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

or

<form action="{{ route('route_name') }}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Regards!

How to use pull to refresh in Swift?

func pullToRefresh(){

    let refresh = UIRefreshControl()
    refresh.addTarget(self, action: #selector(handleTopRefresh(_:)), for: .valueChanged )
    refresh.tintColor = UIColor.appBlack
    self.tblAddressBook.addSubview(refresh)

}
@objc func handleTopRefresh(_ sender:UIRefreshControl){
    self.callAddressBookListApi(isLoaderRequired: false)
    sender.endRefreshing()
}

How to access custom attributes from event object in React?

I think it's recommended to bind all methods where you need to use this.setState method which is defined in the React.Component class, inside the constructor, in your case you constructor should be like

    constructor() {
        super()
        //This binding removeTag is necessary to make `this` work in the callback
        this.removeTag = this.removeTag.bind(this)
    }
    removeTag(event){
        console.log(event.target)
        //use Object destructuring to fetch all element values''
        const {style, dataset} = event.target
        console.log(style)
        console.log(dataset.tag)
    }
   render() {
   ...
      <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
   ...},

For more reference on Object destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

How to autowire RestTemplate using annotations

You can add the method below to your class for providing a default implementation of RestTemplate:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Get a list of numbers as input from the user

you can pass a string representation of the list to json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

user enters in the list as you would in python: [2, 34, 5.6, 90]

how to calculate percentage in python

def percentage_match(mainvalue,comparevalue):
    if mainvalue >= comparevalue:
        matched_less = mainvalue - comparevalue
        no_percentage_matched = 100 - matched_less*100.0/mainvalue
        no_percentage_matched = str(no_percentage_matched) + ' %'
        return no_percentage_matched 
    else:
        print('please checkout your value')

print percentage_match(100,10)
Ans = 10.0 %

How can building a heap be O(n) time complexity?

Basically, work is done only on non-leaf nodes while building a heap...and the work done is the amount of swapping down to satisfy heap condition...in other words (in worst case) the amount is proportional to the height of the node...all in all the complexity of the problem is proportional to the sum of heights of all the non-leaf nodes..which is (2^h+1 - 1)-h-1=n-h-1= O(n)

Make JQuery UI Dialog automatically grow or shrink to fit its contents

This works with jQuery UI v1.10.3

$("selector").dialog({height:'auto', width:'auto'});

fatal: Not a valid object name: 'master'

Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.

Python: Binding Socket: "Address already in use"

You need to set the allow_reuse_address before binding. Instead of the SimpleHTTPServer run this snippet:

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()

This prevents the server from binding before we got a chance to set the flags.

RegEx: Grabbing values between quotation marks

The RegEx of accepted answer returns the values including their sourrounding quotation marks: "Foo Bar" and "Another Value" as matches.

Here are RegEx which return only the values between quotation marks (as the questioner was asking for):

Double quotes only (use value of capture group #1):

"(.*?[^\\])"

Single quotes only (use value of capture group #1):

'(.*?[^\\])'

Both (use value of capture group #2):

(["'])(.*?[^\\])\1

-

All support escaped and nested quotes.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

I think this would be best explained by the following picture:

enter image description here

To initialize the above, one would type:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221)   #top left
fig.add_subplot(222)   #top right
fig.add_subplot(223)   #bottom left
fig.add_subplot(224)   #bottom right 
plt.show()

Monitor network activity in Android Phones

Preconditions: adb and wireshark are installed on your computer and you have a rooted android device.

  1. Download tcpdump to ~/Downloads
  2. adb push ~/Downloads/tcpdump /sdcard/
  3. adb shell
  4. su root
  5. mv /sdcard/tcpdump /data/local/
  6. cd /data/local/
  7. chmod +x tcpdump
  8. ./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
  9. Ctrl+C once you've captured enough data.
  10. exit
  11. exit
  12. adb pull /sdcard/dump.pcap ~/Downloads/

Now you can open the pcap file using Wireshark.

As for your question about monitoring specific processes, find the bundle id of your app, let's call it com.android.myapp

  1. ps | grep com.android.myapp
  2. copy the first number you see from the output. Let's call it 1234. If you see no output, you need to start the app.
  3. Download strace to ~/Downloads and put into /data/local using the same way you did for tcpdump above.
  4. cd /data/local
  5. ./strace -p 1234 -f -e trace=network -o /sdcard/strace.txt

Now you can look at strace.txt for ip addresses, and filter your wireshark log for those IPs.

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

How to create a circle icon button in Flutter?

You just need to use the shape: CircleBorder()

MaterialButton(
  onPressed: () {},
  color: Colors.blue,
  textColor: Colors.white,
  child: Icon(
    Icons.camera_alt,
    size: 24,
  ),
  padding: EdgeInsets.all(16),
  shape: CircleBorder(),
)

enter image description here

Making an image act like a button

It sounds like you want an image button:

<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />

Alternatively, you can use CSS to make the existing submit button use your image as its background.

In any case, you don't want a separate <img /> element on the page.

Auto-expanding layout with Qt-Designer

According to the documentation, there needs to be a top level layout set.

A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.

You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.

Qt layouts

How to Get Element By Class in JavaScript?

_x000D_
_x000D_
var elems = document.querySelectorAll('.one');_x000D_
_x000D_
for (var i = 0; i < elems.length; i++) {_x000D_
    elems[i].innerHTML = 'content';_x000D_
};
_x000D_
_x000D_
_x000D_

Dealing with multiple Python versions and PIP?

/path/to/python2.{5,6} /path/to/pip install PackageName doesn't work?

For this to work on any python version that doesn't have pip already installed you need to download pip and do python*version* setup.py install. For example python3.3 setup.py install. This resolves the import error in the comments. (As suggested by @hbdgaf)

Fastest method to replace all instances of a character in a string

I just coded a benchmark and tested the first 3 answers. It seems that for short strings (<500 characters)
the third most voted answer is faster than the second most voted one.

For long strings (add ".repeat(300)" to the test string) the faster is answer 1 followed by the second and the third.

Note:

The above is true for browsers using v8 engine (chrome/chromium etc).
With firefox (SpiderMonkey engine) the results are totally different
Check for yourselves!! Firefox with the third solution seems to be
more than 4.5 times faster than Chrome with the first solution... crazy :D

_x000D_
_x000D_
function log(data) {_x000D_
  document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
_x000D_
  time_function = function(ms, f, num) {_x000D_
    var z;_x000D_
    var t = new Date().getTime();_x000D_
    for (z = 0;_x000D_
      ((new Date().getTime() - t) < ms); z++) f(num);_x000D_
    return (z / ms)_x000D_
  } // returns how many times the function was run in "ms" milliseconds._x000D_
_x000D_
_x000D_
  function benchmark() {_x000D_
    function compare(a, b) {_x000D_
      if (a[1] > b[1]) {_x000D_
        return -1;_x000D_
      }_x000D_
      if (a[1] < b[1]) {_x000D_
        return 1;_x000D_
      }_x000D_
      return 0;_x000D_
    }_x000D_
_x000D_
    // functions_x000D_
_x000D_
    function replace1(s) {_x000D_
      s.replace(/foo/g, "bar")_x000D_
    }_x000D_
_x000D_
String.prototype.replaceAll2 = function(_f, _r){ _x000D_
_x000D_
  var o = this.toString();_x000D_
  var r = '';_x000D_
  var s = o;_x000D_
  var b = 0;_x000D_
  var e = -1;_x000D_
//      if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }_x000D_
_x000D_
  while((e=s.indexOf(_f)) > -1)_x000D_
  {_x000D_
    r += o.substring(b, b+e) + _r;_x000D_
    s = s.substring(e+_f.length, s.length);_x000D_
    b += e+_f.length;_x000D_
  }_x000D_
_x000D_
  // Add Leftover_x000D_
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }_x000D_
_x000D_
  // Return New String_x000D_
  return r;_x000D_
};_x000D_
_x000D_
String.prototype.replaceAll = function(str1, str2, ignore) {_x000D_
      return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);_x000D_
    }_x000D_
_x000D_
    function replace2(s) {_x000D_
      s.replaceAll("foo", "bar")_x000D_
    }_x000D_
_x000D_
    function replace3(s) {_x000D_
      s.split('foo').join('bar');_x000D_
    }_x000D_
_x000D_
    function replace4(s) {_x000D_
      s.replaceAll2("foo", "bar")_x000D_
    }_x000D_
_x000D_
_x000D_
    funcs = [_x000D_
      [replace1, 0],_x000D_
      [replace2, 0],_x000D_
      [replace3, 0],_x000D_
      [replace4, 0]_x000D_
    ];_x000D_
_x000D_
    funcs.forEach((ff) => {_x000D_
      console.log("Benchmarking: " + ff[0].name);_x000D_
      ff[1] = time_function(2500, ff[0], "foOfoobarBaR barbarfoobarf00".repeat(10));_x000D_
      console.log("Score: " + ff[1]);_x000D_
_x000D_
    })_x000D_
    return funcs.sort(compare);_x000D_
  }_x000D_
_x000D_
  return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
  log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
_x000D_
_x000D_

The test will run for 10s (+2s) as you click the button.

My results (on the same pc):

Chrome/Linux Ubuntu 64:
1. replace1 score: 100% *winner* (766.18)
2. replace4 score: 99.07% speed of winner. (759.11)
3. replace3 score: 68.36% speed of winner. (523.83)
4. replace2 score: 59.35% speed of winner. (454.78)

Firefox/Linux Ubuntu 64
1. replace3 score: 100% *winner* (3480.1)
2. replace1 score: 13.06% speed of winner. (454.83)
3. replace4 score: 9.4% speed of winner. (327.42)
4. replace2 score: 4.81% speed of winner. (167.46)

Nice mess uh?

Took the liberty of adding more test results

Chrome/Windows 10
1. replace1 score: 100% *winner* (742.49)
2. replace4 score: 85.58% speed of winner. (635.44)
3. replace2 score: 54.42% speed of winner. (404.08)
4. replace3 score: 50.06% speed of winner. (371.73)

Firefox/Windows 10
1. replace3 score: 100% *winner* (2645.18)
2. replace1 score: 30.77% speed of winner. (814.18)
3. replace4 score: 22.3% speed of winner. (589.97)
4. replace2 score: 12.51% speed of winner. (331.13)

Edge/Windows 10
1. replace1 score: 100% *winner* (1251.24)
2. replace2 score: 46.63% speed of winner. (583.47)
3. replace3 score: 44.42% speed of winner. (555.92)
4. replace4 score: 20% speed of winner. (250.28)

Chrome on Galaxy Note 4

1. replace4 score: 100% *winner* (99.82)
2. replace1 score: 91.04% speed of winner. (90.88)
3. replace3 score: 70.27% speed of winner. (70.15)
4. replace2 score: 38.25% speed of winner. (38.18)

Spring @Value is not resolving to value from property file

I also found the reason @value was not working is, @value requires PropertySourcesPlaceholderConfigurer instead of a PropertyPlaceholderConfigurer. i did the same changes and it worked for me, i am using spring 4.0.3 release. I configured this using below code in my configuration file -

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

Running shell command and capturing the output

If you need to run a shell command on multiple files, this did the trick for me.

import os
import subprocess

# Define a function for running commands and capturing stdout line by line
# (Modified from Vartec's solution because it wasn't printing all lines)
def runProcess(exe):    
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

# Get all filenames in working directory
for filename in os.listdir('./'):
    # This command will be run on each file
    cmd = 'nm ' + filename

    # Run the command and capture the output line by line.
    for line in runProcess(cmd.split()):
        # Eliminate leading and trailing whitespace
        line.strip()
        # Split the output 
        output = line.split()

        # Filter the output and print relevant lines
        if len(output) > 2:
            if ((output[2] == 'set_program_name')):
                print filename
                print line

Edit: Just saw Max Persson's solution with J.F. Sebastian's suggestion. Went ahead and incorporated that.

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

iframe refuses to display

It means that the http server at cw.na1.hgncloud.com send some http headers to tell web browsers like Chrome to allow iframe loading of that page (https://cw.na1.hgncloud.com/crossmatch/) only from a page hosted on the same domain (cw.na1.hgncloud.com) :

Content-Security-Policy: frame-ancestors 'self' https://cw.na1.hgncloud.com
X-Frame-Options: ALLOW-FROM https://cw.na1.hgncloud.com

You should read that :

Easy login script without database

If you don't have a database, where will the PERMANENT record of your users' login data be stored? Sure, while the user is logged in, the minimal user information required for your site to work can be stored in a session or cookie. But after they log out, then what? The session goes away, the cookie can be hacked.

So your user comes back to your site. He tries to log in. What trustworthy thing does your site compare his login info to?

How can I determine the type of an HTML element in JavaScript?

You can use generic code inspection via instanceof:

var e = document.getElementById('#my-element');
if (e instanceof HTMLInputElement) {}         // <input>
elseif (e instanceof HTMLSelectElement) {}    // <select>
elseif (e instanceof HTMLTextAreaElement) {}  // <textarea>
elseif (  ... ) {}                            // any interface

Look here for a complete list of interfaces.

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I just got my GUC232A cable with a molded-in PL2302 converter chip.

In addition to adding myself and br to group dialout, I found this helpful tip in the README.Debian file in /usr/share/doc/bottlerocket:

This package uses debconf to configure the /dev/firecracker symlink, should you need to change the symlink in the future run this command:

dpkg-reconfigure -pmedium bottlerocket

That will then prompt you for your new serial port and modify the symlink. This is required for proper use of bottlerocket.

I did that and voila! bottlerocket is able to communicate with my X-10 devices.

How do I convert a String to an int in Java?

int foo = Integer.parseInt("1234");

Make sure there is no non-numeric data in the string.

Vertically aligning CSS :before and :after content

Using flexboxes did the trick for me:

.pdf:before {
    display: flex;
    align-items: center;
    justify-content: center;
}

Could not obtain information about Windows NT group user

I was having the same issue, which turned out to be caused by the Domain login that runs the SQL service being locked out in AD. The lockout was caused by an unrelated usage of the service account for another purpose with the wrong password.

The errors received from SQL Agent logs did not mention the service account's name, just the name of the user (job owner) that couldn't be authenticated (since it uses the service account to check with AD).

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

Set language for syntax highlighting in Visual Studio Code

In the very right bottom corner, left to the smiley there was the icon saying "Plain Text". When you click it, the menu with all languages appears where you can choose your desired language.

VSCode

Do HttpClient and HttpClientHandler have to be disposed between requests?

If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

  • HttpClient, as an interface, can't call Dispose().
  • Dispose() will be called in a delayed fashion by the Garbage Collector. Or when the program cleans up the object through its destructor.
  • Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.
  • It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.
  • HttpClientHandle allows for Mocking in tests

Print empty line?

Don't do

print("\n")

on the last line. It will give you 2 empty lines.

VS 2017 Git Local Commit DB.lock error on every commit

My automatically generated .gitignore file contained /.vs instead of .vs/. Fixing this typo fixed the problem!

convert UIImage to NSData

Try one of the following, depending on your image format:

UIImageJPEGRepresentation

Returns the data for the specified image in JPEG format.

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality
);

UIImagePNGRepresentation

Returns the data for the specified image in PNG format

NSData * UIImagePNGRepresentation (
   UIImage *image
);

Here the docs.

EDIT:

if you want to access the raw bytes that make up the UIImage, you could use this approach:

CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];

This will give you the low-level representation of the image RGB pixels. (Omit the CFBridgingRelease bit if you are not using ARC).

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

This error may be also related to the fact that you have an error in your "spring.datasource.url" when you gave a wrong db name for example

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How to change working directory in Jupyter Notebook?

I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path

  1. After find the .jupyter folder, check there has “jupyter_notebook_config” file or not. If it is not there then run below command enter image description here After run the command it will create "jupyter_notebook_config.py"

if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor

  1. Open “jupyter_notebook_config.py” file from the the “.jypyter” folder.
  2. After open the file need to update the directory is use for notebooks and kernel. There are so many line in config file so find “#c.NotebookApp.notebook_dir” and update the path enter image description here After: enter image description here Save the file
  3. Now try to create or read some file from the location you set

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

This worked for me:

Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;

Note: It must match with Owner of the schema.

Schema | Name | Type | Owner
--------+--------+-------+----------

If the owner is different, then give all the grants to the current user role from the admin role by :

GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';

Then try to execute the query, it will give the output as it has access to all the relations now.

When should an IllegalArgumentException be thrown?

Treat IllegalArgumentException as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.

I would agree this example is correct:

void setPercentage(int pct) {
    if( pct < 0 || pct > 100) {
         throw new IllegalArgumentException("bad percent");
     }
}

If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:

import com.someoneelse.EmailUtil;

public void scanEmail(String emailStr, InputStream mime) throws ParseException {
    EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}

If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:

/** @param String email An email with an address in the form [email protected]
 * with no nested comments, periods or other nonsense.
 */
public String scanEmail(String email)
  if (!addressIsProperlyFormatted(email)) {
      throw new IllegalArgumentException("invalid address");
  }
  return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
  // Assumes email is valid
  boolean parsesJustFine = true;
  // Parse logic
  if (!parsesJustFine) {
    // As a private method it is an internal error if address is improperly
    // formatted. This is an internal error to the class implementation.
    throw new AssertError("Internal error");
  }
}

This design could go either way.

  • If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use ParseException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.
  • If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.

A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.

Bootstrap - floating navbar button right

You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav"> with navbar-right class to it.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
    <div class="container">_x000D_
      <div class="navbar-header">_x000D_
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
            <span class="sr-only">Toggle navigation</span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
          </button>_x000D_
        <a class="navbar-brand" href="#">Project name</a>_x000D_
      </div>_x000D_
      <div class="collapse navbar-collapse">_x000D_
        <ul class="nav navbar-nav">_x000D_
          <li class="active"><a href="#">Home</a></li>_x000D_
          <li><a href="#about">About</a></li>_x000D_
_x000D_
        </ul>_x000D_
        <ul class="nav navbar-nav navbar-right">_x000D_
          <li><a href="#contact">Contact</a></li>_x000D_
        </ul>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does hash do in python?

TL;DR:

Please refer to the glossary: hash() is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. that is why we use hash(). It's also used to access dict and set elements which are implemented as resizable hash tables in CPython.

Technical considerations

  • usually comparing objects (which may involve several levels of recursion) is expensive.
  • preferably, the hash() function is an order of magnitude (or several) less expensive.
  • comparing two hashes is easier than comparing two objects, this is where the shortcut is.

If you read about how dictionaries are implemented, they use hash tables, which means deriving a key from an object is a corner stone for retrieving objects in dictionaries in O(1). That's however very dependent on your hash function to be collision-resistant. The worst case for getting an item in a dictionary is actually O(n).

On that note, mutable objects are usually not hashable. The hashable property means you can use an object as a key. If the hash value is used as a key and the contents of that same object change, then what should the hash function return? Is it the same key or a different one? It depends on how you define your hash function.

Learning by example:

Imagine we have this class:

>>> class Person(object):
...     def __init__(self, name, ssn, address):
...         self.name = name
...         self.ssn = ssn
...         self.address = address
...     def __hash__(self):
...         return hash(self.ssn)
...     def __eq__(self, other):
...         return self.ssn == other.ssn
... 

Please note: this is all based on the assumption that the SSN never changes for an individual (don't even know where to actually verify that fact from authoritative source).

And we have Bob:

>>> bob = Person('bob', '1111-222-333', None)

Bob goes to see a judge to change his name:

>>> jim = Person('jim bo', '1111-222-333', 'sf bay area')

This is what we know:

>>> bob == jim
True

But these are two different objects with different memory allocated, just like two different records of the same person:

>>> bob is jim
False

Now comes the part where hash() is handy:

>>> dmv_appointments = {}
>>> dmv_appointments[bob] = 'tomorrow'

Guess what:

>>> dmv_appointments[jim] #?
'tomorrow'

From two different records you are able to access the same information. Now try this:

>>> dmv_appointments[hash(jim)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __eq__
AttributeError: 'int' object has no attribute 'ssn'
>>> hash(jim) == hash(hash(jim))
True

What just happened? That's a collision. Because hash(jim) == hash(hash(jim)) which are both integers btw, we need to compare the input of __getitem__ with all items that collide. The builtin int does not have an ssn attribute so it trips.

>>> del Person.__eq__
>>> dmv_appointments[bob]
'tomorrow'
>>> dmv_appointments[jim]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: <__main__.Person object at 0x7f611bd37110>

In this last example, I show that even with a collision, the comparison is performed, the objects are no longer equal, which means it successfully raises a KeyError.

Entity Framework Migrations renaming tables and columns

Nevermind. I was making this way more complicated than it really needed to be.

This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.

public override void Up()
{
    RenameTable("ReportSections", "ReportPages");
    RenameTable("ReportSectionGroups", "ReportSections");
    RenameColumn("ReportPages", "Group_Id", "Section_Id");
}

public override void Down()
{
    RenameColumn("ReportPages", "Section_Id", "Group_Id");
    RenameTable("ReportSections", "ReportSectionGroups");
    RenameTable("ReportPages", "ReportSections");
}

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You should have a table with the list of emails to check. Then do this query:

SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email

Export MySQL database using PHP only

I would Suggest that you do the folllowing,

<?php

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
    $mysqli      = new mysqli($host, $user, $pass, $name);
    $mysqli->select_db($name);
    $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row         = $queryTables->fetch_row())
    {
        $target_tables[] = $row[0];
    }
    if ($tables !== false)
    {
        $target_tables = array_intersect($target_tables, $tables);
    }
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
    foreach ($target_tables as $table)
    {
        $result        = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num      = $mysqli->affected_rows;
        $res           = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine    = $res->fetch_row();
        $content .= "\n\n" . $TableMLine[1] . ";\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
        {
            while ($row = $result->fetch_row())
            { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0)
                {
                    $content .= "\nINSERT INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++)
                {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j]))
                    {
                        $content .= '"' . $row[$j] . '"';
                    }
                    else
                    {
                        $content .= '""';
                    } if ($j < ($fields_amount - 1))
                    {
                        $content.= ',';
                    }
                }
                $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
                {
                    $content .= ";";
                }
                else
                {
                    $content .= ",";
                } $st_counter = $st_counter + 1;
            }
        } $content .="\n\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql";
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
    echo $content;
    exit;
}
?>

The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.

Shell Script Syntax Error: Unexpected End of File

I had this problem when running some script in cygwin. Fixed by running dos2unix on the script, with proper description of problem and solution given in that answer

EnterKey to press button in VBA Userform

Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.

How can I disable the bootstrap hover color for links?

I am not a Bootstrap expert, but it sounds to me that you should define a new class called nohover (or something equivalent) then in your link code add the class as the last attribute value:

<a class="green nohover" href="#">green text</a>
<a class="yellow nohover" href="#">yellow text</a>

Then in your Bootstrap LESS/CSS file, define nohover (using the JSFiddle example above):

a:hover { color: red  }
/* Green */
a.green  { color: green; }
/* Yellow */
a.yellow  { color: yellow; }
a.nohover:hover { color: none;  }

Forked the JSFiddle here: http://jsfiddle.net/9rpkq/

Problems installing the devtools package

For ubuntu users, run this command in your terminal [Tested in UBUNTU 16.04]

sudo apt-get -y install libcurl4-openssl-dev

post this install libraries the way you usually do in R using

install.packages("package name")

How can I parse a local JSON file from assets folder into a ListView?

As Faizan describes in their answer here:

First of all read the Json File from your assests file using below code.

and then you can simply read this string return by this function as

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

and use this method like that

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

For further details regarding JSON Read HERE

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

set.seed(1)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

library(dplyr)
df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

Daemon Threads Explanation

A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.

A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.

How do I reload a page without a POSTDATA warning in Javascript?

you are not forced to use javascript to do every thing. Many problems have easy solutions like this one. you can use this tricky anchor:

<a href=".">Continue</a>

of course I know you may need an automatic solution but this will help in many cases.

good luck

Styling the last td in a table with css

You can use the col element as specified in HTML 4.0 (link). It works in every browser. You can give it an ID or a class or an inline style. only caveat is that it affects the whole column across all rows. Example:

<table>
    <col />
    <col width="50" />
    <col id="anId" />
    <col class="whatever" />
    <col style="border:1px solid #000;" />
    <tbody>
        <tr>
            <td>One</td>
            <td>Two</td>
            <td>Three</td>
            <td>Four</td>
            <td>Five</td>
        </tr>
    </tbody>
</table>

What is the purpose of mvnw and mvnw.cmd files?

These files are from Maven wrapper. It works similarly to the Gradle wrapper.

This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).

The mvnw file is for Linux (bash) and the mvnw.cmd is for the Windows environment.


To create or update all necessary Maven Wrapper files execute the following command:

mvn -N io.takari:maven:wrapper

To use a different version of maven you can specify the version as follows:

mvn -N io.takari:maven:wrapper -Dmaven=3.3.3

Both commands require maven on PATH (add the path to maven bin to Path on System Variables) if you already have mvnw in your project you can use ./mvnw instead of mvn in the commands.

Linq select to new object

The answers here got me close, but in 2016, I was able to write the following LINQ:

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();

Pass a data.frame column name to a function

Another way is to use tidy evaluation approach. It is pretty straightforward to pass columns of a data frame either as strings or bare column names. See more about tidyeval here.

library(rlang)
library(tidyverse)

set.seed(123)
df <- data.frame(B = rnorm(10), D = rnorm(10))

Use column names as strings

fun3 <- function(x, ...) {
  # capture strings and create variables
  dots <- ensyms(...)
  # unquote to evaluate inside dplyr verbs
  summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}

fun3(df, "B")
#>          B
#> 1 1.715065

fun3(df, "B", "D")
#>          B        D
#> 1 1.715065 1.786913

Use bare column names

fun4 <- function(x, ...) {
  # capture expressions and create quosures
  dots <- enquos(...)
  # unquote to evaluate inside dplyr verbs
  summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}

fun4(df, B)
#>          B
#> 1 1.715065

fun4(df, B, D)
#>          B        D
#> 1 1.715065 1.786913
#>

Created on 2019-03-01 by the reprex package (v0.2.1.9000)

Include files from parent or other directory

Here's something I wrote with that problem in mind:

<?
function absolute_include($file)
         {
         /*
         $file is the file url relative to the root of your site.
         Yourdomain.com/folder/file.inc would be passed as
         "folder/file.inc"
         */

         $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

         if($folder_depth == false)
            $folder_depth = 1;

         include(str_repeat("../", $folder_depth - 1) . $file);
         }
?>

hope it helps.

How to restart service using command prompt?

You can start and stop and query services using the SC command. As for innosetup i'm not sure.

CMD: Export all the screen content to a text file

If you are looking for each command separately

To export all the output of the command prompt in text files. Simply follow the following syntax.

C:> [syntax] >file.txt

The above command will create result of syntax in file.txt. Where new file.txt will be created on the current folder that you are in.

For example,

C:Result> dir >file.txt

To copy the whole session, Try this:

Copy & Paste a command session as follows:

1.) At the end of your session, click the upper left corner to display the menu.
Then select.. Edit -> Select all

2.) Again, click the upper left corner to display the menu.
Then select.. Edit -> Copy

3.) Open your favorite text editor and use Ctrl+V or your normal
Paste operation to paste in the text.

How to set the text/value/content of an `Entry` widget using a button in tkinter

You might want to use insert method. You can find the documentation for the Tkinter Entry Widget here.

This script inserts a text into Entry. The inserted text can be changed in command parameter of the Button.

from tkinter import *

def set_text(text):
    e.delete(0,END)
    e.insert(0,text)
    return

win = Tk()

e = Entry(win,width=10)
e.pack()

b1 = Button(win,text="animal",command=lambda:set_text("animal"))
b1.pack()

b2 = Button(win,text="plant",command=lambda:set_text("plant"))
b2.pack()

win.mainloop()

Android getText from EditText field

EditText txt = (EditText)findviewbyid(R.id.txt);

Editable str = txt.getText().toString();

Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);  

toast.show();

Show Image View from file path?

You can use:

ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));

What is the difference between "mvn deploy" to a local repo and "mvn install"?

"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.

The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.

In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.

a tag as a submit button?

Try something like below

 <a href="#" onclick="this.forms['formName'].submit()">Submit</a> 

Handling the window closing event with WPF / MVVM Light Toolkit

Here is an answer according to the MVVM-pattern if you don't want to know about the Window (or any of its event) in the ViewModel.

public interface IClosing
{
    /// <summary>
    /// Executes when window is closing
    /// </summary>
    /// <returns>Whether the windows should be closed by the caller</returns>
    bool OnClosing();
}

In the ViewModel add the interface and implementation

public bool OnClosing()
{
    bool close = true;

    //Ask whether to save changes och cancel etc
    //close = false; //If you want to cancel close

    return close;
}

In the Window I add the Closing event. This code behind doesn't break the MVVM pattern. The View can know about the viewmodel!

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    IClosing context = DataContext as IClosing;
    if (context != null)
    {
        e.Cancel = !context.OnClosing();
    }
}

How to get value at a specific index of array In JavaScript?

shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.

example:

const comps = [{}, {}, {}]
const specComp = comps
                  .map(fn1)
                  .filter(fn2)
                  .shift()

Remember shift mutates the array, which is very different from accessing via an indexer.

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

How can I test a PDF document if it is PDF/A compliant?

A list of PDF/A validators is on the pdfa.org web site here:

verapdf

A free online PDF/A validator is available here:

http://www.validatepdfa.com/

A report on the accuracy of many of these PDF/A validators is available from PDFLib:

https://www.pdflib.com/fileadmin/pdflib/pdf/pdfa/2009-05-04-Bavaria-report-on-PDFA-validation-accuracy.pdf

Se as well:

https://www.pdflib.com/knowledge-base/pdfa/

log4net vs. Nlog

For us, the key difference is in overall perf...

Have a look at Logger.IsDebugEnabled in NLog versus Log4Net, from our tests, NLog has less overhead and that's what we are after (low-latency stuff).

Cheers, Florian

Format JavaScript date as yyyy-mm-dd

If you don't have anything against using libraries, you could just use the Moments.js library like so:

_x000D_
_x000D_
var now = new Date();_x000D_
var dateString = moment(now).format('YYYY-MM-DD');_x000D_
_x000D_
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Update rows in one table with data from another table based on one column in each being equal

You Could always use and leave out the "when not matched section"

merge into table1 FromTable   
   using table2 ToTable
     on     ( FromTable.field1 = ToTable.field1
          and  FromTable.field2 =ToTable.field2)
when Matched then
update set 
  ToTable.fieldr = FromTable.fieldx,
  ToTable.fields = FromTable.fieldy, 
  ToTable.fieldt =  FromTable.fieldz)
when not matched then
  insert  (ToTable.field1,
       ToTable.field2,
       ToTable.fieldr,
       ToTable.fields,
       ToTable.fieldt)
  values (FromTable.field1,
         FromTable.field2,
         FromTable.fieldx,
         FromTable.fieldy,
         FromTable.fieldz);

How to apply color in Markdown?

When you want to use pure Markdown (without nested HTML), you can use Emojis to draw attention to some fragment of the file, i.e. ??WARNING??, IMPORTANT? or NEW.

How to split a string in Ruby and get all items except the first one?

You can also do this:

String is ex="test1, test2, test3, test4, test5"
array = ex.split(/,/)
array.size.times do |i|
  p array[i]
end 

Attempt to set a non-property-list object as an NSUserDefaults

It seems rather wasteful to me to run through the array and encode the objects into NSData yourself. Your error BC_Person is a non-property-list object is telling you that the framework doesn't know how to serialize your person object.

So all that is needed is to ensure that your person object conforms to NSCoding then you can simply convert your array of custom objects into NSData and store that to defaults. Heres a playground:

Edit: Writing to NSUserDefaults is broken on Xcode 7 so the playground will archive to data and back and print an output. The UserDefaults step is included in case its fixed at a later point

//: Playground - noun: a place where people can play

import Foundation

class Person: NSObject, NSCoding {
    let surname: String
    let firstname: String

    required init(firstname:String, surname:String) {
        self.firstname = firstname
        self.surname = surname
        super.init()
    }

    //MARK: - NSCoding -
    required init(coder aDecoder: NSCoder) {
        surname = aDecoder.decodeObjectForKey("surname") as! String
        firstname = aDecoder.decodeObjectForKey("firstname") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(firstname, forKey: "firstname")
        aCoder.encodeObject(surname, forKey: "surname")
    }
}

//: ### Now lets define a function to convert our array to NSData

func archivePeople(people:[Person]) -> NSData {
    let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(people as NSArray)
    return archivedObject
}

//: ### Create some people

let people = [Person(firstname: "johnny", surname:"appleseed"),Person(firstname: "peter", surname: "mill")]

//: ### Archive our people to NSData

let peopleData = archivePeople(people)

if let unarchivedPeople = NSKeyedUnarchiver.unarchiveObjectWithData(peopleData) as? [Person] {
    for person in unarchivedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Failed to unarchive people")
}

//: ### Lets try use NSUserDefaults
let UserDefaultsPeopleKey = "peoplekey"
func savePeople(people:[Person]) {
    let archivedObject = archivePeople(people)
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(archivedObject, forKey: UserDefaultsPeopleKey)
    defaults.synchronize()
}

func retrievePeople() -> [Person]? {
    if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsPeopleKey) as? NSData {
        return NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [Person]
    }
    return nil
}

if let retrievedPeople = retrievePeople() {
    for person in retrievedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Writing to UserDefaults is still broken in playgrounds")
}

And Voila, you have stored an array of custom objects into NSUserDefaults

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

git pull fails "unable to resolve reference" "unable to update local ref"

I had same issue. i follow following steps

1)switch your branch which having issue to other branch

2) delete that branch

3) checkout again.

Note:- You can stash you uncommitted changes and put it back again.

Eclipse returns error message "Java was started but returned exit code = 1"

Please check your computer and if Java JRE not install download and install it.

If install please check is it 32 bit or 64 bit as per your operating system

To check for 32 or 64-bit JVM, run:

$ java -d64 -version

$ java -d32 -version

Error: This Java instance does not support a X-bit JVM. Please install the desired version.

MultipartException: Current request is not a multipart request

That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

Get first element from a dictionary

Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> first = like.Values.First();

subquery in codeigniter active record

$this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE);

Source : http://www.247techblog.com/use-write-sub-queries-codeigniter-active-records-condition-full-explaination/

String replace a Backslash

To Replace backslash at particular location:

if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
    stringValue=stringValue.substring(0,location-1);
}

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

How to catch integer(0)?

another option is rlang::is_empty (useful if you're working in the tidyverse)

The rlang namespace does not seem to be attached when attaching the tidyverse via library(tidyverse) - in this case you use purrr::is_empty, which is just imported from the rlang package.

By the way, rlang::is_empty uses user Gavin's approach.

rlang::is_empty(which(1:3 == 5))
#> [1] TRUE

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

Custom domain for GitHub project pages

I just discovered, after a bit of frustration, that if you're using PairNIC, all you have to do is enable the "Web Forwarding" setting under "Custom DNS" and supply the username.github.io/project address and it will automatically set up both the apex and subdomain records for you. It appears to do exactly what's suggested in the accepted answer. However, it won't let you do the exact same thing by manually adding records. Very strange. Anyway, it took me a while to figure that out, so I thought I'd share to save everyone else the trouble.

Select 2 columns in one and combine them

I hope this answer helps:

SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;

How to convert ISO8859-15 to UTF8?

We have this problem and to solve

Create a script file called to-utf8.sh

#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
 echo "Skipping binary $FILE..."
 exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
  echo "Converting $FILE..."
  mv -f $FILE.tmp $FILE
else
  echo "Error on $FILE"
fi

Set the executable bit

chmod +x to-utf8.sh

Do a conversion

./to-utf8.sh MyFile.txt

If you want to convert all files under a folder, do

find /your/folder/here | xargs -n 1 ./to-utf8.sh

Hope it's help.

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

_x000D_
_x000D_
section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

php string to int

You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

How to use curl to get a GET request exactly same as using Chrome?

If you need to set the user header string in the curl request, you can use the -H option to set user agent like:

curl -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

Updated user-agent form newest Chrome at 02-22-2021


Using a proxy tool like Charles Proxy really helps make short work of something like what you are asking. Here is what I do, using this SO page as an example (as of July 2015 using Charles version 3.10):

  1. Get Charles Proxy running
  2. Make web request using browser
  3. Find desired request in Charles Proxy
  4. Right click on request in Charles Proxy
  5. Select 'Copy cURL Request'

Copy cURL Request example in Charles 3.10.2

You now have a cURL request you can run in a terminal that will mirror the request your browser made. Here is what my request to this page looked like (with the cookie header removed):

curl -H "Host: stackoverflow.com" -H "Cache-Control: max-age=0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" -H "HTTPS: 1" -H "DNT: 1" -H "Referer: https://www.google.com/" -H "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4" -H "If-Modified-Since: Thu, 23 Jul 2015 20:31:28 GMT" --compressed http://stackoverflow.com/questions/28760694/how-to-use-curl-to-get-a-get-request-exactly-same-as-using-chrome

HttpServletRequest - Get query string parameters, no form data

The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.

The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":

GET /persons?age=42

The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":

PUT /persons?age=42

hair=grey

So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.

How do I iterate through table rows and cells in JavaScript?

Try

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}

_x000D_
_x000D_
for (let row of mytab1.rows) _x000D_
{_x000D_
    for(let cell of row.cells) _x000D_
    {_x000D_
       console.log(cell.innerText)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
for ( let [i,row] of [...mytab1.rows].entries() ) _x000D_
{_x000D_
    for( let [j,cell] of [...row.cells].entries() ) _x000D_
    {_x000D_
       console.log(`[${i},${j}] = ${cell.innerText}`)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Labeling file upload button

Pure CSS solution:

_x000D_
_x000D_
.inputfile {_x000D_
  /* visibility: hidden etc. wont work */_x000D_
  width: 0.1px;_x000D_
  height: 0.1px;_x000D_
  opacity: 0;_x000D_
  overflow: hidden;_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
}_x000D_
.inputfile:focus + label {_x000D_
  /* keyboard navigation */_x000D_
  outline: 1px dotted #000;_x000D_
  outline: -webkit-focus-ring-color auto 5px;_x000D_
}_x000D_
.inputfile + label * {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<input type="file" name="file" id="file" class="inputfile">_x000D_
<label for="file">Choose a file (Click me)</label>
_x000D_
_x000D_
_x000D_

source: http://tympanus.net/codrops

Launch Bootstrap Modal on page load

Just add the following-

class="modal show"

Working Example-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal show" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

how to force maven to update local repo

If you are installing into local repository, there is no special index/cache update needed.

Make sure that:

  1. You have installed the first artifact in your local repository properly. Simply copying the file to .m2 may not work as expected. Make sure you install it by mvn install

  2. The dependency in 2nd project is setup correctly. Check on any typo in groupId/artifactId/version, or unmatched artifact type/classifier.

How to use doxygen to create UML class diagrams from C++ source

Hmm, this seems to be a bit of an old question, but since I've been messing about with Doxygen configuration last few days, while my head's still full of current info let's have a stab at it -

I think the previous answers almost have it:

The missing option is to add COLLABORATION_GRAPH = YES in the Doxyfile. I assume you can do the equivalent thing somewhere in the doxywizard GUI (I don't use doxywizard).

So, as a more complete example, typical "Doxyfile" options related to UML output that I tend to use are:

EXTRACT_ALL          = YES
CLASS_DIAGRAMS      = YES
HIDE_UNDOC_RELATIONS = NO
HAVE_DOT             = YES
CLASS_GRAPH          = YES
COLLABORATION_GRAPH  = YES
UML_LOOK             = YES
UML_LIMIT_NUM_FIELDS = 50
TEMPLATE_RELATIONS   = YES
DOT_GRAPH_MAX_NODES  = 100
MAX_DOT_GRAPH_DEPTH  = 0
DOT_TRANSPARENT      = YES

These settings will generate both "inheritance" (CLASS_GRAPH=YES) and "collaboration" (COLLABORATION_GRAPH=YES) diagrams.

Depending on your target for "deployment" of the doxygen output, setting DOT_IMAGE_FORMAT = svg may also be of use. With svg output the diagrams are "scalable" instead of the fixed resolution of bitmap formats such as .png. Apparently, if viewing the output in browsers other than IE, there is also INTERACTIVE_SVG = YES which will allow "interactive zooming and panning" of the generated svg diagrams. I did try this some time ago, and the svg output was very visually attractive, but at the time, browser support for svg was still a bit inconsistent, so hopefully that situation may have improved lately.

As other comments have mentioned, some of these settings (DOT_GRAPH_MAX_NODES in particular) do have potential performance impacts, so YMMV.

I tend to hate "RTFM" style answers, so apologies for this sentence, but in this case the Doxygen documentation really is your friend, so check out the Doxygen docs on the above mentioned settings- last time I looked you can find the details at http://www.doxygen.nl/manual/config.html.

ignoring any 'bin' directory on a git project

Literally none of the answers actually worked for me; the only one that worked for me was (on Linux):

**/bin
(yes without the / in the end)

git version 2.18.0 

Subprocess changing directory

I guess these days you would do:

import subprocess

subprocess.run(["pwd"], cwd="sub-dir")

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Why is MySQL InnoDB insert so slow?

What's your innodb buffer-pool size? Make sure you've set it to 75% of your RAM. Usually inserts are better when in primary key order for InnoDB. But with a big pool-size, you should see good speeds.

How to get twitter bootstrap modal to close (after initial launch)

Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh

I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:

HTML (modal footer):

 <div class="modal-footer form-footer"><br>
              <span class="caption">
                <button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart&nbsp; <i class="fa fa-shopping-cart"></i></button>     
                <button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel&nbsp; <i class="fa fa-close"></i></a>
              </span>
      </div>

jQUERY:

$(document).ready(function(){
// Allow enter key to trigger preloadorders form
    $(document).keypress(function(e) {       
      if(e.which == 13) {   
          e.preventDefault();   
                if($(".trigger").is(".ok")) 
                   $("#PreLoadOrders").trigger("click");
                else
                    return;
      }
    });
});

As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":

HTML:

<div class="modal-footer caption">
                <button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
            </div>

jQuery (include global.inc):

  $(document).ready(function(){
         // Allow enter key to trigger a particular button anywhere on page
        $(document).keypress(function(e) {
                if(e.which == 13) {
                   if($(".modal").is(":visible")){   
                        $(".modal:visible").find(".modal-close").trigger('click');
                    }
                }
         });
    });

What is "not assignable to parameter of type never" error in typescript?

I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way

const [items , setItems] = useState([]);

and update the state like this:

 const item = { id : new Date().getTime() , text : 'New Text' };
 setItems([ item , ...items ]);

I was getting error:

Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'

but if do it like this,

const [items , setItems] = useState([{}]);

Error is gone but there is an item at 0 index which don't have any data(don't want that).

so the solution I found is:

const [items , setItems] = useState([] as any);

How can the default node version be set using NVM?

Alert: This answer is for MacOS only

Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0

And, v15.4.0 is default

> nvm list
       v13.10.1
->      v15.4.0
         system
default -> 15.4.0 (-> v15.4.0)

And, you want to switch the default to v13.10.1

Follow these steps on your Mac terminal:

  1. Run the command:

    nvm alias default 13.10.1

This will make the default point to v13.10.1 as...

default -> 13.10.1 (-> v13.10.1)
  1. Open new instance of terminal. Now check the node version here as...

node -v

You will get...

v13.10.1
  1. nvm list will also show the new default version.

    nvm list

Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v

Gradients in Internet Explorer 9

Use an Gradient Generator - and everything will be perfect ;) http://www.colorzilla.com/gradient-editor/

Quantile-Quantile Plot using SciPy

To add to the confusion around Q-Q plots and probability plots in the Python and R worlds, this is what the SciPy manual says:

"probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot."

If you try out scipy.stats.probplot, you'll see that indeed it compares a dataset to a theoretical distribution. Q-Q plots, OTOH, compare two datasets (samples).

R has functions qqnorm, qqplot and qqline. From the R help (Version 3.6.3):

qqnorm is a generic function the default method of which produces a normal QQ plot of the values in y. qqline adds a line to a “theoretical”, by default normal, quantile-quantile plot which passes through the probs quantiles, by default the first and third quartiles.

qqplot produces a QQ plot of two datasets.

In short, R's qqnorm offers the same functionality that scipy.stats.probplot provides with the default setting dist=norm. But the fact that they called it qqnorm and that it's supposed to "produce a normal QQ plot" may easily confuse users.

Finally, a word of warning. These plots don't replace proper statistical testing and should be used for illustrative purposes only.

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I solve this issue by switching from .NET 4.7.2 => .NET 4.5.2 and then switch back to 472. So in some cases this error occurs because package manager unable resolve dependences

Prevent typing non-numeric in input type number

This solution seems to be working well for me. It builds on @pavok's solution by preserving ctrl key commands.

document.querySelector("input").addEventListener("keypress", function (e) {
  if (
    e.key.length === 1 && e.key !== '.' && isNaN(e.key) && !e.ctrlKey || 
    e.key === '.' && e.target.value.toString().indexOf('.') > -1
  ) {
    e.preventDefault();
  }
});

Get index of selected option with jQuery

I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.

var vOptionSelect = "#productcodeSelect1";

The index is returned with:

$(vOptionSelect).find(":selected").index();

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

[contains(text(),'')] only returns true or false. It won't return any element results.

Bootstrap Accordion button toggle "data-parent" not working

Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.

$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
    var parent = $(this).data('parent');
    var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
    items.each(function() {
        var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
        $(target).filter('.in').collapse('hide');
    });
});

EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:

$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
    var parent = $(this).data('parent');
    var target = $(this).data('target') || $(this).prop('hash');
    $(parent).find('.collapse.in').not(target).collapse('hide');
});

Finding the number of non-blank columns in an Excel sheet using VBA

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

How to create a String with carriage returns?

Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.

Warning comparison between pointer and integer

This: "\0" is a string, not a character. A character uses single quotes, like '\0'.

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

Find and replace with a newline in Visual Studio Code

CTRL + H, then select regex (*) and write \n

Shorter version: CTRL+H ALT+R \n

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

Databinding an enum property to a ComboBox in WPF

Code

    public enum RULE
    {
        [Description( "?????, ??? ???????????" )]
        any,
        [Description( "????? ???? ????? ??? ? ???" )]
        anyThree,
        [Description( "????????, ??? ???????????" )]
        nearAny,
        [Description( "???????? ???? ????? ??? ? ???" )]
        nearThree
    }

    class ExtendRULE
    {
        public static object Values
        {
            get
            {
                List<object> list = new List<object>();
                foreach( RULE rule in Enum.GetValues( typeof( RULE ) ) )
                {
                    string desc = rule.GetType().GetMember( rule.ToString() )[0].GetCustomAttribute<DescriptionAttribute>().Description;
                    list.Add( new { value = rule, desc = desc } );
                }
                return list;
            }
        }
    }

XAML

<StackPanel>
   <ListBox ItemsSource= "{Binding Source={x:Static model:ExtendRULE.Values}}" DisplayMemberPath="desc" SelectedValuePath="value" SelectedValue="{Binding SelectedRule}"/>
   <ComboBox ItemsSource="{Binding Source={x:Static model:ExtendRULE.Values}}" DisplayMemberPath="desc" SelectedValuePath="value" SelectedValue="{Binding SelectedRule}"/>                        
</StackPanel>

Iterating through array - java

Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:

public static boolean inArray(int[] array, int check) {
   for (int o : array){
      if (o == check) {
         return true;
      }
   }
   return false;
}

In Java 8 you can also do something like:

// import java.util.stream.IntStream;

public static boolean inArray(int[] array, int check) {
   return IntStream.of(array).anyMatch(val -> val == check);
}

Although converting to a stream for this is probably overkill.

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

How to get folder path from file path with CMD

The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:

@echo off
setlocal enabledelayedexpansion enableextensions

set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof

:file_name_from_path <resultVar> <pathVar>
(
    set "%~1=%~nx2"
    exit /b
)

:eof
endlocal

Now the :file_name_from_path function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.

How to check the installed version of React-Native

You can also open your package.json file in node_modules -> react-native.

The version is at the top:

 {
  "name": "react-native",
  "version": "0.12.0",
  ...
 }

Resize font-size according to div size

I found a way of resizing font size according to div size, without any JavaScript. I don't know how much efficient it's, but it nicely gets the job done.

Embed a SVG element inside the required div, and then use a foreignObject tag inside which you can use HTML elements. A sample code snippet that got my job done is given below.

<!-- The SVG element given below should be place inside required div tag -->
<svg viewBox='0 2 108.5 29' xmlns='http://www.w3.org/2000/svg'>
    <!-- The below tag allows adding HTML elements inside SVG tag -->
    <foreignObject x='5' y='0' width='93.5%' height='100%'>
        <!-- The below tag can be styled using CSS classes or style attributes -->
        <div xmlns='http://www.w3.org/1999/xhtml' style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;'>
            Required text goes here            
        </div>
    </foreignObject>
</svg>

All the viewBox, x, y, width and height values can be changed according to requirement.

Text can be defined inside the SVG element itself, but when the text overflows, ellipsis can't be added to SVG text. So, HTML element(s) are defined inside a foreignObject element, and text-overflow styles are added to that/those element(s).

How do I best silence a warning about unused variables?

Your current solution is best - comment out the parameter name if you don't use it. That applies to all compilers, so you don't have to use the pre-processor to do it specially for GCC.

Cannot open include file with Visual Studio

If your problem is still there it's certainly because you are trying to compile a different version from your current settings.

For example if you set your Additional Include Directories in Debug x64, be sure that you are compiling with the same configuration.

Check this: Build > Configuration Manager... > There is problably something like this in your active solution configuration: Debug x86 (Win32) platform.

Javascript : array.length returns undefined

It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.

As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:

json_encode($something) 

with something like:

json_encode(array_values($something))

But don't ignore the other answers here about Object.keys. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

nodejs mongodb object id to string

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

object._id ? object._id.toHexString():object.toHexString();

This is because object._id exists only if the object is populated, if not the object is an ObjectId

How to send data to COM PORT using JAVA?

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

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

Wordpress - Images not showing up in the Media Library

I had this problem with wordpress 3.8.1 and it turned out that my functions.php wasn't saved as utf-8. Re-saved it and it

Easiest way to flip a boolean value?

Easiest solution that I found:

x ^= true;

How to exit an application properly

In a console application, just return from the main program, in a UI-Application Close() all active Forms.

Memory from managed objects will be handled by the .NET Framework, you don't need to care about this.

If you use classes which implement IDisposable (like database connections, for example), you should call Dispose() on them when you no longer need them (preferred way: a using-Statement).

If you use such resources globally (like private members in your form), your form should implement the IDisposable pattern to release these resources on the Close()-call. See this article for details.

Datagridview: How to set a cell in editing mode?

private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.

value.ToUniversalTime().ToString("O");

Click events on Pie Charts in Chart.js

If you are using TypeScript, the code is a little funky because there is no type inference, but this works to get the index of the data that has been supplied to the chart: // events public chartClicked(e:any):void { //console.log(e);

    try {
        console.log('DS ' + e.active['0']._datasetIndex);
        console.log('ID ' +  e.active['0']._index);
        console.log('Label: ' + this.doughnutChartLabels[e.active['0']._index]);
        console.log('Value: ' + this.doughnutChartData[e.active['0']._index]);


    } catch (error) {
        console.log("Error In LoadTopGraph", error);
    }

    try {
        console.log(e[0].active);
    } catch (error) {
        //console.log("Error In LoadTopGraph", error);
    }



}

C++ Matrix Class

The library called, Matrix supports so many features including mathematics operations, dumping and logging features, associative containers, multiple dimensions and etc.

Usage

its usage is similar to c++ arrays.

Matrix<int> A(1, 2);
Matrix<int> B(2, 3);
Matrix<int> result(1, 3);

A[0][0] = 7;
A[0][1] = 10;

B[0][0] = 1;
B[0][1] = 4;
B[0][2] = 2;
B[1][0] = 1;
B[1][1] = 2;
B[1][2] = 100;

result = A * B;

result.dump.matrix();

Result:

Matrix view:
-            -
| 17 48 1014 |
-            -

Here is the documentation and Github page.

How should strace be used?

In simple words, strace traces all system calls issued by a program along with their return codes. Think things such as file/socket operations and a lot more obscure ones.

It is most useful if you have some working knowledge of C since here system calls would more accurately stand for standard C library calls.

Let's say your program is /usr/local/bin/cough. Simply use:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

to write into 'out_file'.

All strace output will go to stderr (beware, the sheer volume of it often asks for a redirection to a file). In the simplest cases, your program will abort with an error and you'll be able to see what where its last interactions with the OS in strace output.

More information should be available with:

man strace