Programs & Examples On #Sql agent

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

How do I fix a NoSuchMethodError?

I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.

Filtering Pandas DataFrames on dates

How about using pyjanitor

It has cool features.

After pip install pyjanitor

import janitor

df_filtered = df.filter_date(your_date_column_name, start_date, end_date)

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

What is the most efficient way to loop through dataframes with pandas?

For sure, the fastest way to iterate over a dataframe is to access the underlying numpy ndarray either via df.values (as you do) or by accessing each column separately df.column_name.values. Since you want to have access to the index too, you can use df.index.values for that.

index = df.index.values
column_of_interest1 = df.column_name1.values
...
column_of_interestk = df.column_namek.values

for i in range(df.shape[0]):
   index_value = index[i]
   ...
   column_value_k = column_of_interest_k[i]

Not pythonic? Sure. But fast.

If you want to squeeze more juice out of the loop you will want to look into cython. Cython will let you gain huge speedups (think 10x-100x). For maximum performance check memory views for cython.

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

How do I set hostname in docker-compose?

This seems to work correctly. If I put your config into a file:

$ cat > compose.yml <<EOF
dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock
EOF

And then bring things up:

$ docker-compose -f compose.yml up
Creating tmp_dns_1...
Attaching to tmp_dns_1
dns_1 | 2015-04-28T17:47:45.423387 [dockerdns] table.add tmp_dns_1.docker -> 172.17.0.5

And then check the hostname inside the container, everything seems to be fine:

$ docker exec -it stack_dns_1 hostname
affy.affy.com

JavaScript for...in vs for

Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.

Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:

for (var name in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, name)) {
        // DO STUFF
    }
}

Listing all extras of an Intent

The Kotlin version of Pratik's utility method which dumps all extras of an Intent:

fun dumpIntent(intent: Intent) {

    val bundle: Bundle = intent.extras ?: return

    val keys = bundle.keySet()
    val it = keys.iterator()

    Log.d(TAG, "Dumping intent start")

    while (it.hasNext()) {
        val key = it.next()
        Log.d(TAG,"[" + key + "=" + bundle.get(key)+"]");
    }

    Log.d(TAG, "Dumping intent finish")

}

What is the difference between "::" "." and "->" in c++

-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member

How to Use Order By for Multiple Columns in Laravel 4?

Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:

public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
    $result = $this->model->with($with);
    $dataSet = $result->where($where)
        // Conditionally use $orderBy if not empty
        ->when(!empty($orderBy), function ($query) use ($orderBy) {
            // Break $orderBy into pairs
            $pairs = array_chunk($orderBy, 2);
            // Iterate over the pairs
            foreach ($pairs as $pair) {
                // Use the 'splat' to turn the pair into two arguments
                $query->orderBy(...$pair);
            }
        })
        ->paginate($limit)
        ->appends(Input::except('page'));

    return $dataSet;
}

Now, you can make your call like this:

$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

Add characters to a string in Javascript

To use String.concat, you need to replace your existing text, since the function does not act by reference.

var text ="";
for (var member in list) {
        text = text.concat(list[member]);
}

Of course, the join() or += suggestions offered by others will work fine as well.

What is a singleton in C#?

E.X You can use Singleton for global information that needs to be injected.

In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.

public class SysManager
{
    private static readonly SysManager_instance = new SysManager();

    static SysManager() {}

    private SysManager(){}

    public static SysManager Instance
    {
        get {return _instance;}
    }
}

http://csharpindepth.com/Articles/General/Singleton.aspx#cctor

ASP.NET Core 1.0 on IIS error 502.5

I solved it by adding "edit permission" to the application of the site, mapped to the physical directory and then selected the windows user that could have access to this root folder. (private network).

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

"detached entity passed to persist error" with JPA/EJB code

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

click command in selenium webdriver does not work

Thanks for all the answers everyone! I have found a solution, turns out I didn't provide enough code in my question.

The problem was NOT with the click() function after all, but instead related to cas authentication used with my project. In Selenium IDE my login test executed a "open" command to the following location,

/cas/login?service=https%1F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security

That worked. I exported the test to Selenium webdriver which naturally preserved that location. The command in Selenium Webdriver was,

driver.get(baseUrl + "/cas/login?service=https%1A%2F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security");

For reasons I have yet to understand the above failed. When I changed it to,

driver.get(baseUrl + "MOREURL/");

The click command suddenly started to work... I will edit this answer if I can figure out why exactly this is.

Note: I obscured the URLs used above to protect my company's product.

Convert an array into an ArrayList

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

default value for struct member in C

Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
So no this is not possible in C.

Instead you can write a function which does the initialization for structure instance.

Alternatively, You could do:

struct MyStruct_s 
{
    int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

And then always initialize your new instances as:

MyStruct mInstance = MyStruct_default;

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

Artisan, creating tables in database

in laravel 5 first we need to create migration and then run the migration

Step 1.

php artisan make:migration create_users_table --create=users

Step 2.

php artisan migrate

Why would an Enum implement an Interface?

The post above that mentioned strategies didn't stress enough what a nice lightweight implementation of the strategy pattern using enums gets you:

public enum Strategy {

  A {
    @Override
    void execute() {
      System.out.print("Executing strategy A");
    }
  },

  B {
    @Override
    void execute() {
      System.out.print("Executing strategy B");
    }
  };

  abstract void execute();
}

You can have all your strategies in one place without needing a separate compilation unit for each. You get a nice dynamic dispatch just with:

Strategy.valueOf("A").execute();

Makes java read almost like a nice loosely typed language!

What is meant with "const" at end of function declaration?

Function can't change its parameters via the pointer/reference you gave it.

I go to this page every time I need to think about it:

http://www.parashift.com/c++-faq-lite/const-correctness.html

I believe there's also a good chapter in Meyers' "More Effective C++".

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

How can I make a button have a rounded border in Swift?

I have created a simple UIButton sublcass that uses the tintColor for its text and border colours and when highlighted changes its background to the tintColor.

class BorderedButton: UIButton {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    layer.borderWidth = 1.0
    layer.borderColor = tintColor.CGColor
    layer.cornerRadius = 5.0
    clipsToBounds = true
    contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    setTitleColor(tintColor, forState: .Normal)
    setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
    setBackgroundImage(UIImage(color: tintColor), forState: .Highlighted)
}
}

This makes use of a UIImage extension that creates an image from a colour, I found that code here: https://stackoverflow.com/a/33675160

It works best when set to type Custom in interface builder as the default System type slightly modifies the colours when the button is highlighted.

What's the quickest way to multiply multiple cells by another number?

  1. Enter the multiplier in a cell
  2. Copy that cell to the clipboard
  3. Select the range you want to multiply by the multiplier
  4. (Excel 2003 or earlier) Choose Edit | Paste Special | Multiply

    (Excel 2007 or later) Click on the Paste down arrow | Paste Special | Multiply

loading json data from local file into React JS

I was trying to do the same thing and this is what worked for me (ES6/ES2015):

import myData from './data.json';

I got the solution from this answer on a react-native thread asking the same thing: https://stackoverflow.com/a/37781882/176002

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

How to get the filename without the extension from a path in Python?

Very very very simpely no other modules !!!

import os
p = r"C:\Users\bilal\Documents\face Recognition python\imgs\northon.jpg"

# Get the filename only from the initial file path.
filename = os.path.basename(p)

# Use splitext() to get filename and extension separately.
(file, ext) = os.path.splitext(filename)

# Print outcome.
print("Filename without extension =", file)
print("Extension =", ext)

Do subclasses inherit private fields?

Memory Layout in Java vis-a-vis inheritance

enter image description here

Padding bits/Alignment and the inclusion of Object Class in the VTABLE is not considered. So the object of the subclass does have a place for the private members of the Super class. However, it cannot be accessed from the subclass's objects...

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

UTF-8 byte[] to String

To convert utf-8 data, you can't assume a 1-1 correspondence between bytes and characters. Try this:

String file_string = new String(bytes, "UTF-8");

(Bah. I see I'm way to slow in hitting the Post Your Answer button.)

To read an entire file as a String, do something like this:

public String openFileToString(String fileName) throws IOException
{
    InputStream is = new BufferedInputStream(new FileInputStream(fileName));

    try {
        InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
        StringBuilder contents = new StringBuilder();
        char[] buff = new char[4096];
        int len = rdr.read(buff);
        while (len >= 0) {
            contents.append(buff, 0, len);
        }
        return buff.toString();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // log error in closing the file
        }
    }
}

How do you validate a URL with a regular expression in Python?

An easy way to parse (and validate) URL's is the urlparse (py2, py3) module.

A regex is too much work.


There's no "validate" method because almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

Bottom Line. Parse it, and look at the pieces to see if they're displeasing in some way.

Do you want the scheme to always be "http"? Do you want the netloc to always be "www.somename.somedomain"? Do you want the path to look unix-like? Or windows-like? Do you want to remove the query string? Or preserve it?

These are not RFC-specified validations. These are validations unique to your application.

How to count the number of columns in a table using SQL?

select count(*) 
from user_tab_columns
where table_name='MYTABLE' --use upper case

Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';

Is it a good practice to place C++ definitions in header files?

I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.

By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.

change the date format in laravel view page

Method One:

Using the strtotime() to time is the best format to change the date to the given format.

strtotime() - Parse about any English textual datetime description into a Unix timestamp

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

Example:

<?php
$timestamp = strtotime( "February 26, 2007" );  
print date('Y-m-d', $timestamp );
?>

Output:

2007-02-26

Method Two:

date_format() - Return a new DateTime object, and then format the date:

<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>

Output:

 2013/03/15 00:00:00 

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

How to define a two-dimensional array?

Try this:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

How to configure the web.config to allow requests of any length

HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.

To resolve this problem, check in the source code whether the Form tag has a property method is get/set state.

If so, the method property should be removed.

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

How to use RANK() in SQL Server

Select T.Tamil, T.English, T.Maths, T.Total, Dense_Rank()Over(Order by T.Total Desc) as Std_Rank From (select Tamil,English,Maths,(Tamil+English+Maths) as Total From Student) as T

enter image description here

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

How to insert an item into a key/value pair object?

You could use an OrderedDictionary, but I would question why you would want to do that.

Where does SVN client store user authentication data?

  • On Unix, it's in $HOME/.subversion/auth.

  • On Windows, I think it's: %APPDATA%\Subversion\auth.

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

PHP Get all subdirectories of a given directory

The Spl DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        echo $fileinfo->getFilename().'<br>';
    }
}

Using node.js as a simple web server

Step1 (inside command prompt [I hope you cd TO YOUR FOLDER]) : npm install express

Step 2: Create a file server.js

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder

app.get("/", function(request, response){ //root dir
    response.send("Hello!!");
});

app.listen(port, host);

Please note, you should add WATCHFILE (or use nodemon) too. Above code is only for a simple connection server.

STEP 3: node server.js or nodemon server.js

There is now more easy method if you just want host simple HTTP server. npm install -g http-server

and open our directory and type http-server

https://www.npmjs.org/package/http-server

Why there is no ConcurrentHashSet against ConcurrentHashMap

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

Trigger a button click with JavaScript on the Enter key in a text box

To do it with jQuery:

$("#txtSearch").on("keyup", function (event) {
    if (event.keyCode==13) {
        $("#btnSearch").get(0).click();
    }
});

To do it with normal JavaScript:

document.getElementById("txtSearch").addEventListener("keyup", function (event) {
    if (event.keyCode==13) { 
        document.getElementById("#btnSearch").click();
    }
});

Convert a SQL Server datetime to a shorter date format

Try this:

print cast(getdate() as date )

Flutter - Wrap text on overflow, like insert ellipsis or fade

If you simply place text as a child(ren) of a column, this is the easiest way to have text automatically wrap. Assuming you don't have anything more complicated going on. In those cases, I would think you would create your container sized as you see fit and put another column inside and then your text. This seems to work nicely. Containers want to shrink to the size of its contents, and this seems to naturally conflict with wrapping, which requires more effort.

Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    Text('This long text will wrap very nicely if there isn't room beyond the column\'s total width and if you have enough vertical space available to wrap into.',
      style: TextStyle(fontSize: 16, color: primaryColor),
      textAlign: TextAlign.center,),
  ],
),

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

How to read a file in reverse order?

You can also use python module file_read_backwards.

After installing it, via pip install file_read_backwards (v1.2.1), you can read the entire file backwards (line-wise) in a memory efficient manner via:

#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

It supports "utf-8","latin-1", and "ascii" encodings.

Support is also available for python3. Further documentation can be found at http://file-read-backwards.readthedocs.io/en/latest/readme.html

Creating a class object in c++

1)What is the difference between both the way of creating class objects.

First one is a pointer to a constructed object in heap (by new). Second one is an object that implicitly constructed. (Default constructor)

2)If i am creating object like Example example; how to use that in an singleton class.

It depends on your goals, easiest is put it as a member in class simply.

A sample of a singleton class which has an object from Example class:

class Sample
{

    Example example;

public:

    static inline Sample *getInstance()
    {
        if (!uniqeInstance)
        {
            uniqeInstance = new Sample;
        }
        return uniqeInstance;
    }
private:
    Sample();
    virtual ~Sample();
    Sample(const Sample&);
    Sample &operator=(const Sample &);
    static Sample *uniqeInstance;
};

Basic calculator in Java

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

Is it possible to get an Excel document's row count without loading the entire document into memory?

Python 3

import openpyxl as xl

wb = xl.load_workbook("Sample.xlsx", enumerate)

#the 2 lines under do the same. 
sheet = wb.get_sheet_by_name('sheet') 
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

#this works fore me.

Error in launching AVD with AMD processor

For those who are using Android Studio based on Jetbrains:

  1. Goto Tools > Android > SDK Manager

  2. Under Extras --> select the checkbox Intel x86 Emulator Accelorator

For those who are unable to use Nexus AVD can also try using Generic AVD.

  1. Goto Tools > Android > AVD Manager

Then create a new Genreic AVD with something like QVGA and use for your app. This AVD does not use hardware acceleration.

How to generate a random integer number from within a range

unsigned int
randr(unsigned int min, unsigned int max)
{
       double scaled = (double)rand()/RAND_MAX;

       return (max - min +1)*scaled + min;
}

See here for other options.

Delete files older than 3 months old in a directory using .NET

Here's a 1-liner lambda:

Directory.GetFiles(dirName)
         .Select(f => new FileInfo(f))
         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
         .ToList()
         .ForEach(f => f.Delete());

Using Git with Visual Studio

The newest release of Git Extensions supports Visual Studio 2010 now (along with Visual Studio 2008 and Visual Studio 2005).

I found it to be fairly easy to use with Visual Studio 2008 and the interface seems to be the same in Visual Studio 2010.

Convert a timedelta to days, hours and minutes

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

How do I customize Facebook's sharer.php

Facebook sharer.php parameters for sharing posts.

<a href="javascript: void(0);"
   data-layout="button"
   onclick="window.open('https://www.facebook.com/sharer.php?u=MyPageUrl&summary=MySummary&title=MyTitle&description=MyDescription&picture=MyYmageUrl', 'ventanacompartir', 'toolbar=0, status=0, width=650, height=450');"> Share </a>

Don't use spaces, use &nbsp.

Assigning strings to arrays of characters

There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character \0. Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x[] = {'h','e','l','l','o','\0'};

The correct way would be:

char s[100];
strncpy(s, "hello", 100);

or better yet:

#define STRMAX 100
char    s[STRMAX];
size_t  len;
len = strncpy(s, "hello", STRMAX);

How to append to the end of an empty list?

I personally prefer the + operator than append:

for i in range(0, n):

    list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

Getting the ID of the element that fired an event

In the case of delegated event handlers, where you might have something like this:

<ul>
    <li data-id="1">
        <span>Item 1</span>
    </li>
    <li data-id="2">
        <span>Item 2</span>
    </li>
    <li data-id="3">
        <span>Item 3</span>
    </li>
    <li data-id="4">
        <span>Item 4</span>
    </li>
    <li data-id="5">
        <span>Item 5</span>
    </li>
</ul>

and your JS code like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId = $target.data('id');

        //do something with itemId
    });
});

You'll more than likely find that itemId is undefined, as the content of the LI is wrapped in a <span>, which means the <span> will probably be the event target. You can get around this with a small check, like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
            itemId = $target.data('id');

        //do something with itemId
    });
});

Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId;

        $target = $target.is('li') ? $target : $target.closest('li');
        itemId = $target.data('id');

        //do something with itemId
    });
});

When using event delegation, the .is() method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector) to search up the DOM tree, and use .find(selector) (generally coupled with .first(), as in .find(selector).first()) to search down it. You don't need to use .first() when using .closest(), as it only returns the first matching ancestor element, while .find() returns all matching descendants.

Background thread with QThread in PyQt

Take this answer updated for PyQt5, python 3.4

Use this as a pattern to start a worker that does not take data and return data as they are available to the form.

1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.

2 - The main.py file is the file that defines the GUI Form class

3 - The thread object is not subclassed.

4 - Both thread object and the worker object belong to the Form object

5 - Steps of the procedure are within the comments.

# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time


class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)


    @pyqtSlot()
    def procCounter(self): # A slot takes no params
        for i in range(1, 100):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

And the main file is:

  # main.py
  from PyQt5.QtCore import QThread
  from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
  import sys
  import worker


  class Form(QWidget):

    def __init__(self):
       super().__init__()
       self.label = QLabel("0")

       # 1 - create Worker and Thread inside the Form
       self.obj = worker.Worker()  # no parent!
       self.thread = QThread()  # no parent!

       # 2 - Connect Worker`s Signals to Form method slots to post data.
       self.obj.intReady.connect(self.onIntReady)

       # 3 - Move the Worker object to the Thread object
       self.obj.moveToThread(self.thread)

       # 4 - Connect Worker Signals to the Thread slots
       self.obj.finished.connect(self.thread.quit)

       # 5 - Connect Thread started signal to Worker operational slot method
       self.thread.started.connect(self.obj.procCounter)

       # * - Thread finished signal will close the app if you want!
       #self.thread.finished.connect(app.exit)

       # 6 - Start the thread
       self.thread.start()

       # 7 - Start the form
       self.initUI()


    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label,0,0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()

    def onIntReady(self, i):
        self.label.setText("{}".format(i))
        #print(i)

    app = QApplication(sys.argv)

    form = Form()

    sys.exit(app.exec_())

AutoComplete TextBox Control

    You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
    The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.

    USE [DRDOULATINSTITUTE]
    GO
    /****** Object:  StoredProcedure [dbo].[ReikiInsertRow]    Script Date: 5/18/2016 11:12:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[ReikiInsertRow]
    @Reiki varchar(100),
    @emailadd varchar(50)
    as
    insert into dbo.ReikiPowerDisplay
    select Reiki,ReikiDescription, @emailadd from ReikiPower
    where Reiki=@Reiki;

Posted By: Aneel Goplani. CIS. 2002. USA

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

If you only have to view it, I've used this:

print cast(dbo.f_functiondeliveringbigformattedtext(seed) as text)

The end result is that I get line feeds and all the content in the messages window of SMSS. Of course, it only allows for a single cell - if you want to do a single cell from a number of rows, you could do this:

declare @T varchar(max)=''
select @T=@T
       + isnull(dbo.f_functiondeliveringbigformattedtext(x.a),'NOTHINGFOUND!')
       + replicate(char(13),4)
from x -- table containing multiple rows and a value in column a
print @T

I use this to validate JSON strings generated by SQL code. Too hard to read otherwise!

Using Python to execute a command on every file in a folder

AVI to MPG (pick your extensions):

files = os.listdir('/input')
for sourceVideo in files:
    if sourceVideo[-4:] != ".avi"
        continue
    destinationVideo = sourceVideo[:-4] + ".mpg"
    cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
        '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
    output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
    print output1
    output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
    print output2

open read and close a file in 1 line of code

No need to import any special libraries to do this.

Use normal syntax and it will open the file for reading then close it.

with open("/etc/hostname","r") as f: print f.read() 

or

with open("/etc/hosts","r") as f: x = f.read().splitlines()

which gives you an array x containing the lines, and can be printed like so:

for line in x: print line

These one-liners are very helpful for maintenance - basically self-documenting.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

Change

die (mysqli_error()); 

to

die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
<item>
    <layer-list>
        <item>  
            <shape>
                <gradient 
                    android:startColor="@color/grey_light"
                    android:endColor="@color/grey_dark"
                    android:type="linear"
                    android:angle="270"
                    android:centerColor="@color/grey_mediumtodark" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
        <item>  
            <shape>
                <gradient 
                    android:startColor="#00666666"
                    android:endColor="#77666666"
                    android:type="radial"
                    android:gradientRadius="200"
                    android:centerColor="#00666666"
                    android:centerX="0.5"
                    android:centerY="0" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
    </layer-list>
</item>

Controlling Maven final name of jar artifact

At the package stage, the plugin allows configuration of the imported file names via file mapping:

maven-ear-plugin

http://maven.apache.org/plugins/maven-ear-plugin/examples/customize-file-name-mapping.html

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ear-plugin</artifactId>
    <version>2.7</version>
    <configuration>
       [...]
        <fileNameMapping>full</fileNameMapping>
    </configuration>
</plugin>

http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html#outputFileNameMapping

If you have configured your version to be 'testing' via a profile or something, this would work for a war package:

maven-war-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <encoding>UTF-8</encoding>                        
        <outputFileNameMapping>@{groupId}@-@{artifactId}@-@{baseVersion}@@{dashClassifier?}@.@{extension}@</outputFileNameMapping>
    </configuration>
</plugin>

Run Jquery function on window events: load, resize, and scroll?

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

Differences between fork and exec

The main difference between fork() and exec() is that,

The fork() system call creates a clone of the currently running program. The original program continues execution with the next line of code after the fork() function call. The clone also starts execution at the next line of code. Look at the following code that i got from http://timmurphy.org/2014/04/26/using-fork-in-cc-a-minimum-working-example/

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    printf("--beginning of program\n");
    int counter = 0;
    pid_t pid = fork();
    if (pid == 0)
    {
        // child process
        int i = 0;
        for (; i < 5; ++i)
        {
            printf("child process: counter=%d\n", ++counter);
        }
    }
    else if (pid > 0)
    {
        // parent process
        int j = 0;
        for (; j < 5; ++j)
        {
            printf("parent process: counter=%d\n", ++counter);
        }
    }
    else
    {
        // fork failed
        printf("fork() failed!\n");
        return 1;
    }
    printf("--end of program--\n");
    return 0;
}

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

The exec() family of system calls replaces the currently executing code of a process with another piece of code. The process retains its PID but it becomes a new program. For example, consider the following code:

#include <stdio.h> 
#include <unistd.h> 
main() {
 char program[80],*args[3];
 int i; 
printf("Ready to exec()...\n"); 
strcpy(program,"date"); 
args[0]="date"; 
args[1]="-u"; 
args[2]=NULL; 
i=execvp(program,args); 
printf("i=%d ... did it work?\n",i); 
} 

This program calls the execvp() function to replace its code with the date program. If the code is stored in a file named exec1.c, then executing it produces the following output:

Ready to exec()... 
Tue Jul 15 20:17:53 UTC 2008 

The program outputs the line -Ready to exec() . . . ? and after calling the execvp() function, replaces its code with the date program. Note that the line - . . . did it work? is not displayed, because at that point the code has been replaced. Instead, we see the output of executing -date -u.?

How to create a JSON object

Although the other answers posted here work, I find the following approach more natural:

$obj = (object) [
    'aString' => 'some string',
    'anArray' => [ 1, 2, 3 ]
];

echo json_encode($obj);

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

VBA collection: list of keys

An alternative solution is to store the keys in a separate Collection:

'Initialise these somewhere.
Dim Keys As Collection, Values As Collection

'Add types for K and V as necessary.
Sub Add(K, V) 
Keys.Add K
Values.Add V, K
End Sub

You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

How do I convert a PDF document to a preview image in PHP?

If you're loading the PDF from a blob this is how you get the first page instead of the last page:

$im->readimageblob($blob);
$im->setiteratorindex(0);

Bootstrap control with multiple "data-toggle"

If you want to add a modal and a tooltip without adding javascript or altering the tooltip function, you could also simply wrap an element around it:

<span data-toggle="modal" data-target="modal">
    <a data-toggle="tooltip" data-placement="top" title="Tooltip">
      Hover Me           
    </a>
</span>

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Add days Oracle SQL

You can use the plus operator to add days to a date.

order_date + 20

Iterating through a JSON object

I believe you probably meant:

from __future__ import print_function

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.items():
        print(attribute, value) # example usage

NB: You could use song.iteritems instead of song.items if in Python 2.

How to vertically align a html radio button to it's label?

Something like this should work

CSS:

input {
    float: left;
    clear: left;
    width: 50px;
    line-height: 20px;
}

label {
    float: left;
    vertical-align: middle;
}

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

This function will convert in both directions: 12 to 24 hour or 24 to 12 hour

function toggle24hr(time, onoff){
    if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
    var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
    time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
    time[0] = Number(time[0])
    if(onoff){//convert to 24 hour:
        if((pm && time[0]!=12)) time[0] += 12
        else if(!pm && time[0]==12) time[0] = '00'  //handle midnight
        if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
    }else{ //convert to 12 hour:
        pm = time[0]>=12
        if(!time[0]) time[0]=12 //handle midnight
        else if(pm && time[0]!=12) time[0] -= 12
    }
    return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}

Here's some examples:

//convert to 24 hour:
toggle24hr('12:00am')   //returns 00:00
toggle24hr('2:00pm')    //returns 14:00
toggle24hr('8:00am')    //returns 08:00
toggle24hr('12:00pm')   //returns 12:00

//convert to 12 hour:
toggle24hr('14:00')    //returns 2:00pm
toggle24hr('08:00')    //returns 8:00am
toggle24hr('12:00')    //returns 12:00pm
toggle24hr('00:00')    //returns 12:00am

//you can also force a specific format like this:
toggle24hr('14:00',1)    //returns 14:00
toggle24hr('14:00',0)    //returns 2:00pm

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

How to create an executable .exe file from a .m file

The "StandAlone" method to compile .m file (or files) requires a set of Matlab published library (.dll) files on a target (non-Matlab) platform to allow execution of the compiler generated .exe.

Check MATLAB main site for their compiler products and their limitations.

When to use React "componentDidUpdate" method?

componentDidUpdate(prevProps){ 

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

How can I tell jaxb / Maven to generate multiple schema packages?

you should change that to define the plugin only once and do twice execution areas...like the following...and the generateDirectory should be set (based on the docs)..

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.1</version>
  <executions>
    <execution>
      <id>firstrun</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generateDirectory>target/gen1</generateDirectory>
        <schemaDirectory>src/main/resources/dir1</schemaDirectory>
        <schemaIncludes>
          <include>schema1.xsd</include>
        </schemaIncludes>
        <generatePackage>schema1.package</generatePackage>
      </configuration>
    </execution>
    <execution>
      <id>secondrun</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generateDirectory>target/gen2</generateDirectory>
        <schemaDirectory>src/main/resources/dir2</schemaDirectory>
        <schemaIncludes>
          <include>schema2.xsd</include>
        </schemaIncludes>
        <generatePackage>schema2.package</generatePackage>
      </configuration>
    </execution>
  </executions>
</plugin>

It seemed to me that you are fighting against single artifact rule of maven...may be you should think about this.

Test if characters are in a string

You want grepl:

> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE

Line break (like <br>) using only css

You can use ::after to create a 0px-height block after the <h4>, which effectively moves anything after the <h4> to the next line:

_x000D_
_x000D_
h4 {_x000D_
  display: inline;_x000D_
}_x000D_
h4::after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    Text, text, text, text, text. <h4>Sub header</h4>_x000D_
    Text, text, text, text, text._x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to make CSS width to fill parent?

EDIT:

Those three different elements all have different rendering rules.

So for:

table#bar you need to set the width to 100% otherwise it will be only be as wide as it determines it needs to be. However, if the table rows total width is greater than the width of bar it will expand to its needed width. IF i recall you can counteract this by setting display: block !important; though its been awhile since ive had to fix that. (im sure someone will correct me if im wrong).

textarea#bar i beleive is a block level element so it will follow the rules the same as the div. The only caveat here is that textarea take an attributes of cols and rows which are measured in character columns. If this is specified on the element it will override the width specified by the css.

input#bar is an inline element, so by default you cant assign it width. However the similar to textarea's cols attribute, it has a size attribute on the element that can determine width. That said, you can always specifiy a width by using display: block; in your css for it. Then it will follow the same rendering rules as the div.

td#foo will be rendered as a table-cell which has some craziness to it. Bottom line here is that for your purposes its going to act just like div#foo as far as restricting the width of its contents. The only issue here is going to be potential unwrappable text in the column somewhere which would make it ignore your width setting. Also all cells in the column are going to get the width of the widest cell.


Thats the default behavior of block level element - ie. if width is auto (the default) then it will be 100% of the inner width of the containing element. so in essence:

#foo {width: 800px;}
#bar {padding-left: 2px; padding-right: 2px; margin-left: 2px; margin-right: 2px;}

will give you exactly what you want.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

What is the difference between linear regression and logistic regression?

Logistic Regression is used in predicting categorical outputs like Yes/No, Low/Medium/High etc. You have basically 2 types of logistic regression Binary Logistic Regression (Yes/No, Approved/Disapproved) or Multi-class Logistic regression (Low/Medium/High, digits from 0-9 etc)

On the other hand, linear regression is if your dependent variable (y) is continuous. y = mx + c is a simple linear regression equation (m = slope and c is the y-intercept). Multilinear regression has more than 1 independent variable (x1,x2,x3 ... etc)

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

By using the requestInterceptor, it worked for me:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

Equivalent of varchar(max) in MySQL?

The max length of a varchar is

65535

divided by the max byte length of a character in the character set the column is set to (e.g. utf8=3 bytes, ucs2=2, latin1=1).

minus 2 bytes to store the length

minus the length of all the other columns

minus 1 byte for every 8 columns that are nullable. If your column is null/not null this gets stored as one bit in a byte/bytes called the null mask, 1 bit per column that is nullable.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

If you can discount transient outages on the remote server you are trying to connect to, then that just leaves the local network config as a problem.

Using the IP address instead of the hostname is only going to work for the default domain on the remote host.

What happens when you try using www.google.com (or its IP address)? If you stil can't connect, then its something to do with the network between your server and the outside world.

Downloading a file from spring controllers

This code is working fine to download a file automatically from spring controller on clicking a link on jsp.

@RequestMapping(value="/downloadLogFile")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
    try {
        String filePathToBeServed = //complete file name with path;
        File fileToDownload = new File(filePathToBeServed);
        InputStream inputStream = new FileInputStream(fileToDownload);
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt"); 
        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
        inputStream.close();
    } catch (Exception e){
        LOGGER.debug("Request could not be completed at this moment. Please try again.");
        e.printStackTrace();
    }

}

In MySQL, can I copy one row to insert into the same table?

I just had to do this and this was my manual solution:

  1. In phpmyadmin, check the row you wish to copy
  2. At the bottom under query result operations click 'Export'
  3. On the next page check 'Save as file' then click 'Go'
  4. Open the exported file with a text editor, find the value of the primary field and change it to something unique.
  5. Back in phpmyadmin click on the 'Import' tab, locate the file to import .sql file under browse, click 'Go' and the duplicate row should be inserted.

If you don't know what the PRIMARY field is, look back at your phpmyadmin page, click on the 'Structure' tab and at the bottom of the page under 'Indexes' it will show you which 'Field' has a 'Keyname' value 'PRIMARY'.

Kind of a long way around, but if you don't want to deal with markup and just need to duplicate a single row there you go.

Getting URL parameter in java and extract a specific text from that URL

Import these libraries

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.

public static List<NameValuePair> getQueryMap(String query)  
{  
    List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
    String[] params = query.split(Pattern.quote("&"));  
    for (String param : params)
    {
        String[] chunks = param.split(Pattern.quote("="));
        String name = chunks[0], value = null;  
        if(chunks.length > 1) {
            value = chunks[1];
        }
        queryMap.add(new BasicNameValuePair(name, value));
    }
    return queryMap;
}

Example:

GET /bottom.gif?e235c08=1509896923&%49%6E%...

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

Change icon-bar (?) color in bootstrap

I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,

**<Div class = "navbar"**>
         div class = "container">
               <Div class = "navbar-header">

or

**<Div class = "navbar navbar-default">**
        div class = "container">
               <Div class = "navbar-header">

You got that place in your CSS

.navbar-default-toggle .navbar .icon-bar {
  background-color: # 0000ff;
}

and what I did was add above

.navbar .navbar-toggle .icon-bar {
  background-color: # ff0000;
}

Because my html code is

**<Div class = "navbar">**
         div class = "container">
               <Div class = "navbar-header">

and if you associate a file less / css

search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;

if your html code is like mine and is not navbar-default, add it as you did with the css.

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;

good luck

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

How to get a product's image in Magento?

You need set image type :small_image or image

echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Efficient way of having a function only execute once in a loop

You can also use one of the standard library functools.lru_cache or functools.cache decorators in front of the function:

from functools import lru_cache

@lru_cache def expensive_function(): return None

https://docs.python.org/3/library/functools.html

Storing database records into array

$memberId =$_SESSION['TWILLO']['Id'];

    $QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
    $data = array();
    while($ser=mysql_fetch_assoc($QueryServer))
    {

     $data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');

    }

What is Vim recording and how can it be disabled?

Typing q starts macro recording, and the recording stops when the user hits q again.

As Joey Adams mentioned, to disable recording, add the following line to .vimrc in your home directory:

map q <Nop>

What is the meaning of "this" in Java?

It refers to the current instance of a particular object, so you could write something like

public Object getMe() {
    return this;
}

A common use-case of this is to prevent shadowing. Take the following example:

public class Person {
    private final String name;

    public Person(String name) {
        // how would we initialize the field using parameter?
        // we can't do: name = name;
    }
}

In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }
}

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Define width of .absorbing-column

Set table-layout to auto and define an extreme width on .absorbing-column.

Here I have set the width to 100% because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.

This is one of the quirky benefits of how tables behave. The table-layout: auto algorithm is mathematically forgiving.

You may even choose to define a min-width on all td elements to prevent them from becoming too narrow and the table will behave nicely.

_x000D_
_x000D_
table {_x000D_
    table-layout: auto;_x000D_
    border-collapse: collapse;_x000D_
    width: 100%;_x000D_
}_x000D_
table td {_x000D_
    border: 1px solid #ccc;_x000D_
}_x000D_
table .absorbing-column {_x000D_
    width: 100%;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Why does dividing two int not yield the right value when assigned to double?

In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.

One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading

void foo(int);
void foo(double);

void (*p)(double) = &foo; // automatically selects `foo(fouble)`

This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.

IIS Request Timeout on long ASP.NET operation

If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.

For example:

// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;

This value can also be configured in your web.config file in the httpRuntime configuration element:

<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300" 
  ... other configuration attributes ...
/>

enter image description here

Please note according to the MSDN documentation:

"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."

If you've already done this but are finding that your session is expiring then increase the ASP.NET HttpSessionState.Timeout value:

For example:

// Increase session timeout to thirty minutes
Session.Timeout = 30;

This value can also be configured in your web.config file in the sessionState configuration element:

<configuration>
  <system.web>
    <sessionState 
      mode="InProc"
      cookieless="true"
      timeout="30" />
  </system.web>
</configuration>

If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.

The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.

How to add parameters into a WebRequest?

If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.

If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

How to call an element in a numpy array?

Also, you could try to use ndarray.item(), for example, arr.item((0, 0))(rowid+colid to index) or arr.item(0)(flatten index), its doc https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html

How to drop all tables from the database with manage.py CLI in Django?

simple(?) way to do it from python (on mysql):

from django.db import connection

cursor = connection.cursor()
cursor.execute('show tables;')
parts = ('DROP TABLE IF EXISTS %s;' % table for (table,) in cursor.fetchall())
sql = 'SET FOREIGN_KEY_CHECKS = 0;\n' + '\n'.join(parts) + 'SET FOREIGN_KEY_CHECKS = 1;\n'
connection.cursor().execute(sql)

How can I view an object with an alert()

you can use the JSON.stringify() method found in modern browsers and provided by json2.js.

var myObj = {"myProp":"Hello"};
alert (JSON.stringify(myObj));    // alerts {"myProp":"Hello"};

or

also check this library : http://devpro.it/JSON/files/JSON-js.html

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

Stop form from submitting , Using Jquery

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Bootstrap 3 Navbar Collapse

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!

Can git undo a checkout of unstaged files

If you are working in an editor like Sublime Text, and have file in question still open, you can press ctrl+z, and it will return to the state it had before git checkout.

How do I pause my shell script for a second before continuing?

I realize that I'm a bit late with this, but you can also call sleep and pass the disired time in. For example, If I wanted to wait for 3 seconds I can do:

/bin/sleep 3

4 seconds would look like this:

/bin/sleep 4

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Function to Calculate a CRC16 Checksum

There are several details you need to 'match up' with for a particular CRC implementation - even using the same polynomial there can be different results because of minor differences in how data bits are handled, using a particular initial value for the CRC (sometimes it's zero, sometimes 0xffff), and/or inverting the bits of the CRC. For example, sometimes one implementation will work from the low order bits of the data bytes up, while sometimes they'll work from the high order bits down (as yours currently does).

Also, you need to 'push out' the last bits of the CRC after you've run all the data bits through.

Keep in mind that CRC algorithms were designed to be implemented in hardware, so some of how bit ordering is handled may not make so much sense from a software point of view.

If you want to match the CRC16 with polynomial 0x8005 as shown on the lammertbies.nl CRC calculator page, you need to make the following changes to your CRC function:

  • a) run the data bits through the CRC loop starting from the least significant bit instead of from the most significant bit
  • b) push the last 16 bits of the CRC out of the CRC register after you've finished with the input data
  • c) reverse the CRC bits (I'm guessing this bit is a carry over from hardware implementations)

So, your function might look like:

#define CRC16 0x8005

uint16_t gen_crc16(const uint8_t *data, uint16_t size)
{
    uint16_t out = 0;
    int bits_read = 0, bit_flag;

    /* Sanity check: */
    if(data == NULL)
        return 0;

    while(size > 0)
    {
        bit_flag = out >> 15;

        /* Get next bit: */
        out <<= 1;
        out |= (*data >> bits_read) & 1; // item a) work from the least significant bits

        /* Increment bit counter: */
        bits_read++;
        if(bits_read > 7)
        {
            bits_read = 0;
            data++;
            size--;
        }

        /* Cycle check: */
        if(bit_flag)
            out ^= CRC16;

    }

    // item b) "push out" the last 16 bits
    int i;
    for (i = 0; i < 16; ++i) {
        bit_flag = out >> 15;
        out <<= 1;
        if(bit_flag)
            out ^= CRC16;
    }

    // item c) reverse the bits
    uint16_t crc = 0;
    i = 0x8000;
    int j = 0x0001;
    for (; i != 0; i >>=1, j <<= 1) {
        if (i & out) crc |= j;
    }

    return crc;
}

That function returns 0xbb3d for me when I pass in "123456789".

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I met the same problem and I resolved it by setting CopyLocal to true for the following libs:

System.Web.Http.dll
System.Web.Http.WebHost.dll
System.Net.Http.Formatting.dll

I must to add that I use MVC4 and NET 4

CSS white space at bottom of page despite having both min-height and height tag

It is happening Due to:

<p><script>var _nwls=[];if(window.jQuery&&window.jQuery.find){_nwls=jQuery.find(".fw_link_newWindow");}else{if(document.getElementsByClassName){_nwls=document.getElementsByClassName("fw_link_newWindow");}else{if(document.querySelectorAll){_nwls=document.querySelectorAll(".fw_link_newWindow");}else{document.write('<scr'+'ipt src="http://static.websimages.com/static/global/js/sizzle/sizzle.min.js"><\/scr'+'ipt>');if(window.Sizzle){_nwls=Sizzle(".fw_link_newWindow");}}}}var numlinks=_nwls.length;for(var i=0;i<numlinks;i++){_nwls[i].target="_blank";}</script></p>

Remove <p></p> around the script.

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

Similarity String Comparison in Java

Theoretically, you can compare edit distances.

How to find the port for MS SQL Server 2008?

In addition to what is listed above, I had to enable both TCP and UDP ports for SQLExpress to connect remotely. Because I have three different instances on my development machine, I enable 1430-1435 for both TCP and UDP.

Return in Scala

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

How can I avoid running ActiveRecord callbacks?

I wrote a plugin that implements update_without_callbacks in Rails 3:

http://github.com/dball/skip_activerecord_callbacks

The right solution, I think, is to rewrite your models to avoid callbacks in the first place, but if that's impractical in the near term, this plugin may help.

Detect all Firefox versions in JS

This script detects all versions of Firefox, for Desktop, from version 1 to 46.

It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.

I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.

_x000D_
_x000D_
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
    // Match UserAgent string with Firefox Desktop_x000D_
    // Detect hybrid Gecko browsers and mobile_x000D_
    if (navigator.userAgent.match(/firefox/i) &&_x000D_
        !navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
        // Create Element and Array to test availability  _x000D_
        var createdElement = document.createElement('div'),_x000D_
            createdArray = [],_x000D_
            firefoxVersion = "0";_x000D_
_x000D_
        // Firefox 1.0 released November 9, 2004 _x000D_
        // Check a current feature as being true, or NOT undefined _x000D_
        // AND check future features as EQUAL undefined_x000D_
        if (typeof window.alert !== "undefined" &&_x000D_
            typeof window.XPCNativeWrapper === "undefined" &&_x000D_
            typeof window.URL === "undefined") {_x000D_
            firefoxVersion = "1";_x000D_
        }_x000D_
_x000D_
        // Firefox 1.5 released October 15, 2003 _x000D_
        // XPCNativeWrapper used to create security wrapper_x000D_
        else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
            typeof window.globalStorage === "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "1.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 2 released October 24, 2006_x000D_
        // globalStorage later deprecated in favor of localstorage_x000D_
        else if (typeof window.globalStorage !== "undefined" &&_x000D_
            typeof window.postMessage === "undefined") {_x000D_
            firefoxVersion = "2";_x000D_
        }_x000D_
_x000D_
        // Firefox 3 released June 17, 2008_x000D_
        // postMessage for cross window messaging_x000D_
        else if (typeof window.postMessage !== "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "3";_x000D_
        }_x000D_
_x000D_
        // Firefox 3.5 released June 30, 2009_x000D_
        // querySelector returns list of the elements from document_x000D_
        else if (typeof document.querySelector !== "undefined" &&_x000D_
            typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "3.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 4 released March 22, 2011_x000D_
        // window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
        else if (typeof window.URL !== "undefined" &&_x000D_
            typeof createdElement.style.MozAnimation === "undefined") {_x000D_
            firefoxVersion = "4";_x000D_
        }_x000D_
_x000D_
        // After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
        // Firefox 5 released June 21, 2011_x000D_
        // style.MozAnimation for CSS animation, renamed to style.animation_x000D_
        else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
            typeof WeakMap === "undefined") {_x000D_
            firefoxVersion = "5";_x000D_
        }_x000D_
_x000D_
        // Firefox 6 released August 16, 2011_x000D_
        // WeakMap collects key value pairs weakly referenced_x000D_
        else if (typeof WeakMap !== "undefined" &&_x000D_
            typeof createdElement.style.textOverflow === "undefined") {_x000D_
            firefoxVersion = "6";_x000D_
        }_x000D_
_x000D_
        // Firefox 7 released September 27, 2011_x000D_
        // textOverflow manages overflowed non displayed content_x000D_
        else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
            typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
            firefoxVersion = "7";_x000D_
        }_x000D_
_x000D_
        // Firefox 8 released November 8, 2011_x000D_
        // insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
        // faster than direct innerHTML manipulation and_x000D_
        // appends without affecting other elements under the same parent_x000D_
        else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
            typeof navigator.doNotTrack === "undefined") {_x000D_
            firefoxVersion = "8";_x000D_
        }_x000D_
_x000D_
        // Firefox 9 released December 20, 2011_x000D_
        // mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
        // IndexDB improved functionality than localstorage_x000D_
        else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
            typeof document.mozFullScreenEnabled === "undefined") {_x000D_
            firefoxVersion = "9";_x000D_
        }_x000D_
_x000D_
        // Firefox 10 released January 31, 2012_x000D_
        // mozFullScreenEnabled reports if full-screen mode is available_x000D_
        else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
            typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "10";_x000D_
        }_x000D_
_x000D_
        // Firefox 11 released March 13, 2012_x000D_
        // mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
        // Cancels an animation frame request_x000D_
        else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
            typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
            firefoxVersion = "11";_x000D_
        }_x000D_
_x000D_
        // Firefox 12 released April 24, 2012_x000D_
        // MozTextAlignLast how the last line is aligned_x000D_
        else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
            typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
            firefoxVersion = "12";_x000D_
        }_x000D_
_x000D_
        // Firefox 13 released June 5, 2012_x000D_
        // MozOpacity dropped from this version_x000D_
        else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
            typeof window.globalStorage !== "undefined") {_x000D_
            firefoxVersion = "13";_x000D_
        }_x000D_
_x000D_
        // Firefox 14 released June 26, 2012_x000D_
        // globalStorage dropped from this version_x000D_
        else if (typeof window.globalStorage === "undefined" &&_x000D_
            typeof createdElement.style.borderImage === "undefined" &&_x000D_
            typeof document.querySelector !== "undefined") {_x000D_
            firefoxVersion = "14";_x000D_
        }_x000D_
_x000D_
        // Firefox 15 released August 28, 2012_x000D_
        // borderImage allows drawing an image on the borders of elements_x000D_
        else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined") {_x000D_
            firefoxVersion = "15";_x000D_
        }_x000D_
_x000D_
        // Firefox 16 released October 9, 2012_x000D_
        // animation was MozAnimation_x000D_
        else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
            typeof createdElement.style.iterator === "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "16";_x000D_
        }_x000D_
_x000D_
        // Firefox 17 released November 20, 2012_x000D_
        // version 27 drops iterator and renames italic_x000D_
        // Used to iterate over enumerable properties of an object_x000D_
        else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined") {_x000D_
            firefoxVersion = "17";_x000D_
        }_x000D_
_x000D_
        // Firefox 18 released January 8, 2013_x000D_
        // devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
        else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
            typeof window.getInterface === "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "18";_x000D_
        }_x000D_
_x000D_
        // Firefox 19 released February 19, 2013_x000D_
        // getInterface dropped and renamed in version 32_x000D_
        // Retrieves specified interface pointers_x000D_
        else if (typeof window.getInterface !== "undefined" &&_x000D_
            typeof Math.imul === "undefined") {_x000D_
            firefoxVersion = "19";_x000D_
        }_x000D_
_x000D_
        // Firefox 20 released April 2, 2013_x000D_
        // Math.imul provides fast 32 bit integer multiplication_x000D_
        else if (typeof Math.imul !== "undefined" &&_x000D_
            typeof window.crypto.getRandomValues === "undefined") {_x000D_
            firefoxVersion = "20";_x000D_
        }_x000D_
_x000D_
        // Firefox 21 released May 14, 2013_x000D_
        // getRandomValues lets you get cryptographically random values_x000D_
        else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
            typeof createdElement.style.flex === "undefined") {_x000D_
            firefoxVersion = "21";_x000D_
        }_x000D_
_x000D_
        // Firefox 22 released June 25, 2013_x000D_
        // flex can alter dimensions to fill available space_x000D_
        else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
            typeof window.cancelAnimationFrame === "undefined") {_x000D_
            firefoxVersion = "22";_x000D_
        }_x000D_
_x000D_
        // Firefox 23 released August 6, 2013_x000D_
        // cancelAnimationFrame was mozCancelAnimationFrame_x000D_
        else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "23";_x000D_
        }_x000D_
_x000D_
        // Firefox 24 released September 17, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        // loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
        else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "24";_x000D_
        }_x000D_
_x000D_
        // Firefox 25 released October 29, 2013_x000D_
        // Math.trunc returns number removing fractional digits_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined") {_x000D_
            firefoxVersion = "25";_x000D_
        }_x000D_
_x000D_
        // Firefox 26 released December 10, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "26";_x000D_
        }_x000D_
_x000D_
        // Firefox 27 released February 4, 2014_x000D_
        // Math.hypot returns square root of the sum of squares_x000D_
        else if (typeof Math.hypot !== "undefined" &&_x000D_
            typeof createdArray.entries === "undefined") {_x000D_
            firefoxVersion = "27";_x000D_
        }_x000D_
_x000D_
        // Firefox 28 released March 18, 2014_x000D_
        // entries returns key value pairs for arrays_x000D_
        else if (typeof createdArray.entries !== "undefined" &&_x000D_
            typeof createdElement.style.boxSizing === "undefined") {_x000D_
            firefoxVersion = "28";_x000D_
        }_x000D_
_x000D_
        // Firefox 29 released April 29, 2014_x000D_
        // boxSizing alters CSS box model, calculates width and height of elements_x000D_
        else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
            typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
            firefoxVersion = "29";_x000D_
        }_x000D_
_x000D_
        // Firefox 30 released June 10, 2014_x000D_
        // backgroundBlendMode blends elements background images_x000D_
        else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
            typeof createdElement.style.paintOrder === "undefined") {_x000D_
            firefoxVersion = "30";_x000D_
        }_x000D_
_x000D_
        // Firefox 31 released July 22, 2014_x000D_
        // paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
        else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "31";_x000D_
        }_x000D_
_x000D_
        // Firefox 32 released September 2, 2014_x000D_
        // mixBlendMode how an element should blend _x000D_
        else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
            typeof Number.toInteger !== "undefined") {_x000D_
            firefoxVersion = "32";_x000D_
        }_x000D_
_x000D_
        // Firefox 33 released October 14, 2014_x000D_
        // numberToIntger dropped, used to convert values to integer_x000D_
        else if (typeof Number.toInteger === "undefined" &&_x000D_
            typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
            firefoxVersion = "33";_x000D_
        }_x000D_
_x000D_
        // Firefox 34 released December 1, 2014_x000D_
        // fontFeatureSettings control over advanced typographic features_x000D_
        else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
            typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
            firefoxVersion = "34";_x000D_
        }_x000D_
_x000D_
        // Firefox 35 released January 13, 2015_x000D_
        // mozIsLocallyAvailable dropped_x000D_
        else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
            firefoxVersion = "35";_x000D_
        }_x000D_
_x000D_
        // Firefox 36 released February 24, 2015_x000D_
        // quote returns a copy of the string_x000D_
        else if (typeof String.quote !== "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
            firefoxVersion = "36";_x000D_
        }_x000D_
_x000D_
        // Firefox 37 released March 31, 2015_x000D_
        // quote quickly dropped_x000D_
        else if (typeof String.quote === "undefined" &&_x000D_
            typeof createdElement.style.rubyPosition === "undefined") {_x000D_
            firefoxVersion = "37";_x000D_
        }_x000D_
_x000D_
        // Firefox 38 released May 12, 2015_x000D_
        // rubyPosition defines position of a ruby element relative to its base element_x000D_
        else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
            typeof window.Headers === "undefined") {_x000D_
            firefoxVersion = "38";_x000D_
        }_x000D_
_x000D_
        // Firefox 39 released July 2, 2015_x000D_
        // Headers allows us to create our own headers objects _x000D_
        else if (typeof window.Headers !== "undefined" &&_x000D_
            typeof Symbol.match === "undefined") {_x000D_
            firefoxVersion = "39";_x000D_
        }_x000D_
_x000D_
        // Firefox 40 released August 11, 2015_x000D_
        // match matches a regular expression against a string_x000D_
        else if (typeof Symbol.match !== "undefined" &&_x000D_
            typeof Symbol.species === "undefined") {_x000D_
            firefoxVersion = "40";_x000D_
        }_x000D_
_x000D_
        // Firefox 41 released September 22, 2015_x000D_
        // species allows subclasses to over ride the default constructor_x000D_
        else if (typeof Symbol.species !== "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "41";_x000D_
        }_x000D_
_x000D_
        // Firefox 42 released November 3, 2015_x000D_
        // mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
        // Reflect offers methods for interceptable JavaScript operations_x000D_
        else if (typeof Reflect !== "undefined" &&_x000D_
            typeof window.screen.orientation === "undefined") {_x000D_
            firefoxVersion = "42";_x000D_
        }_x000D_
_x000D_
        // Firefox 43 released December 15, 2015_x000D_
        // orientation is mozOrientation in B2G and Android_x000D_
        else if (typeof window.screen.orientation !== "undefined" &&_x000D_
            typeof document.charset === "undefined") {_x000D_
            firefoxVersion = "43";_x000D_
        }_x000D_
_x000D_
        // Firefox 44 released January 26, 2016_x000D_
        // charset is for legacy, use document.characterSet_x000D_
        else if (typeof document.charset !== "undefined" &&_x000D_
            typeof window.onstorage === "undefined") {_x000D_
            firefoxVersion = "44";_x000D_
        }_x000D_
_x000D_
        // Firefox 45 released March 8, 2016_x000D_
        // onstorage contains an event handler that runs when the storage event fires_x000D_
        else if (typeof window.onstorage !== "undefined" &&_x000D_
            typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
            firefoxVersion = "45";_x000D_
        }_x000D_
_x000D_
        // Firefox 46 - beta_x000D_
        // onabsolutedeviceorientation_x000D_
        else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
            firefoxVersion = "46 or above";_x000D_
        }_x000D_
_x000D_
        // Else could not verify_x000D_
        else {_x000D_
            outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
        }_x000D_
_x000D_
        // Display Firefox version_x000D_
        outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
        // Else not detected_x000D_
    } else {_x000D_
        outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
    }_x000D_
} catch (e) {_x000D_
    // Statement to handle exceptions_x000D_
    outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
_x000D_
_x000D_

class method generates "TypeError: ... got multiple values for keyword argument ..."

Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration - it's a common error when one's in a hurry).

Anaconda-Navigator - Ubuntu16.04

Try this:

First go to the anaconda3 binaries directory by running

 cd anaconda3/bin

and now use this following command to open the anaconda-navigator

./anaconda-navigator

How to debug SSL handshake using cURL?

openssl s_client -connect 127.0.0.1:6379 -state
CONNECTED(00000003)
SSL_connect:before SSL initialization
SSL_connect:SSLv3/TLS write client hello

How can I import Swift code to Objective-C?

Go to build settings in your project file and search for "Objective-C Generated Interface Header Name. The value of that property is the name that you should include.

If your "Product Module Name" property (the one that the above property depends on by default) varies depending on whether you compile for test/debug/release/etc (like it does in my case), then make this property independent of that variation by setting a custom name.

C# cannot convert method to non delegate type

You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.

string t = obj.getTitle();

Extra Non-Essential Information

Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle() and setTitle(string value), but you could do it like this:

public string Title // Note: public fields, methods and properties use PascalCasing
{
    get // This replaces your getTitle method
    {
        return _title; // Where _title is a field somewhere
    }
    set // And this replaces your setTitle method
    {
        _title = value; // value behaves like a method parameter
    }
}

Or you could use auto-implemented properties, which would use this by default:

public string Title { get; set; }

And you wouldn't have to create your own backing field (_title), the compiler would create it itself.

Also, you can change access levels for property accessors (getters and setters):

public string Title { get; private set; }

You use properties as if they were fields, i.e.:

this.Title = "Example";
string local = this.Title;

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble returns a primitive double containing the value of the string:

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

valueOf returns a Double instance, if already cached, you'll get the same cached instance.

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

To avoid the overhead of creating a new Double object instance, you should normally use valueOf

Unzip files programmatically in .net

String ZipPath = @"c:\my\data.zip";
String extractPath = @"d:\\myunzips";
ZipFile.ExtractToDirectory(ZipPath, extractPath);

To use the ZipFile class, you must add a reference to the System.IO.Compression.FileSystem assembly in your project

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

Using Jasmine to spy on a function without an object

A very simple way:

import * as myFunctionContainer from 'whatever-lib';

const fooSpy = spyOn(myFunctionContainer, 'myFunc');

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

How to add action listener that listens to multiple buttons

There is no this pointer in a static method. (I don't believe this code will even compile.)

You shouldn't be doing these things in a static method like main(); set things up in a constructor. I didn't compile or run this to see if it actually works, but give it a try.

public class Calc extends JFrame implements ActionListener {

    private Button button1;

    public Calc()
    {
        super();
        this.setSize(100, 100);
        this.setVisible(true);

        this.button1 = new JButton("1");
        this.button1.addActionListener(this);
        this.add(button1);
    }


    public static void main(String[] args) {

        Calc calc = new Calc();
        calc.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button1)
    }  

}

Sorting int array in descending order

Guava has a method Ints.asList() for creating a List<Integer> backed by an int[] array. You can use this with Collections.sort to apply the Comparator to the underlying array.

List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());

Note that the latter is a live list backed by the actual array, so it should be pretty efficient.

ModuleNotFoundError: What does it mean __main__ is not a package?

I have the same issue as you did. I think the problem is that you used relative import in in-package import. There is no __init__.py in your directory. So just import as Moses answered above.

The core issue I think is when you import with a dot:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

It is equivalent to:

from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after

where __main__ refers to your current module p_03_using_bisection_search.py.


Briefly, the interpreter does not know your directory architecture.

When the interpreter get in p_03.py, the script equals:

from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after

and p_03_using_bisection_search does not contain any modules or instances called p_02_paying_debt_off_in_a_year.


So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):

The main architecture of the directory is:

main.py
setup.py
problem_set_02/
   __init__.py
   p01.py
   p02.py
   p03.py

Then write in __init__.py:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

Here __main__ is __init__ , it exactly refers to the module problem_set_02.

Then go to main.py:

import problem_set_02

You can also write a setup.py to add specific module to the environment.

How to animate RecyclerView items when they appear

Made Simple with XML only

Visit Gist Link

res/anim/layout_animation.xml

<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

res/anim/item_animation_fall_down.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

Use in layouts and recylcerview like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layout_animation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

How can I remove text within parentheses with a regex?

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

Create a table without a header in Markdown

Universal Solution

Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.

What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->'):

| <!-- -->    | <!-- -->    |
|-------------|-------------|
| Foo         | Bar         |

Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

For an easy fix, you could

echo 1 > /proc/sys/vm/overcommit_memory

if your're sure that your system has enough memory. See Linux over commit heuristic.

Use dynamic variable names in `dplyr`

You may enjoy package friendlyeval which presents a simplified tidy eval API and documentation for newer/casual dplyr users.

You are creating strings that you wish mutate to treat as column names. So using friendlyeval you could write:

multipetal <- function(df, n) {
  varname <- paste("petal", n , sep=".")
  df <- mutate(df, !!treat_string_as_col(varname) := Petal.Width * n)
  df
}

for(i in 2:5) {
  iris <- multipetal(df=iris, n=i)
}

Which under the hood calls rlang functions that check varname is legal as column name.

friendlyeval code can be converted to equivalent plain tidy eval code at any time with an RStudio addin.

How to check the installed version of React-Native

Just Do a "npm audit" on your project directory and then go to your project package.json file. In the package.json file you will find all the versions and the package names.This should work irrespective of the OS.

How to stop a JavaScript for loop?

The logic is incorrect. It would always return the result of last element in the array.

remIndex = -1;

for (i = 0; i < remSize.length; i++) {      
    if (remSize[i].size == remData.size) {
        remIndex = i
        break;
    }
}

How can I echo the whole content of a .html file in PHP?

You should use readfile():

readfile("/path/to/file");

This will read the file and send it to the browser in one command. This is essentially the same as:

echo file_get_contents("/path/to/file");

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

How to remove last n characters from every element in the R vector

Here is an example of what I would do. I hope it's what you're looking for.

char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)

a should now contain:

  data data2
1 foo_ 1
2 bar_ 2
3   ap 3
4    b 4

How to disable right-click context-menu in JavaScript

If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.

In Excel, sum all values in one column in each row where another column is a specific value

You could do this using SUMIF. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:

 -   A         B
 1   100       YES
 2   100       YES
 3   100       NO

Using the formula: =SUMIF(B1:B3, "YES", A1:A3), you will get the result of 200.

Here's a screenshot of a working example I just did in Excel:

Excel SUMIF Example

SQL Select between dates

Change your data to that formats to use sqlite datetime formats.

YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD

SELECT * FROM test WHERE date BETWEEN '2011-01-11' AND '2011-08-11'

Python error message io.UnsupportedOperation: not readable

You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

file = open("File.txt","r")

Additionally, here are the other options:

"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing.  The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.

toggle show/hide div with button?

JavaScript - Toggle Element.styleMDN

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
  display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

About the ^ bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

JavaScript - Toggle .classList.toggle()

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.classList.toggle("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle

.toggle()Docs; .fadeToggle()Docs; .slideToggle()Docs

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
  display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle .toggleClass()Docs

.toggle() toggles an element's display "block"/"none" values

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

HTML5 - Toggle using <summary> and <details>

(unsupported on IE and Opera Mini)

_x000D_
_x000D_
<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>
_x000D_
_x000D_
_x000D_

HTML - Toggle using checkbox

_x000D_
_x000D_
[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
_x000D_
_x000D_

HTML - Switch using radio

_x000D_
_x000D_
[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_

CSS - Switch using :target

(just to make sure you have it in your arsenal)

_x000D_
_x000D_
[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_


Animating class transition

If you pick one of JS / jQuery way to actually toggle a className, you can always add animated transitions to your element, here's a basic example:

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function(){
  content.classList.toggle("appear");
}, false);
_x000D_
#content{
  /* DON'T USE DISPLAY NONE/BLOCK! Instead: */
  background: #cf5;
  padding: 10px;
  position: absolute;
  visibility: hidden;
  opacity: 0;
          transition: 0.6s;
  -webkit-transition: 0.6s;
          transform: translateX(-100%);
  -webkit-transform: translateX(-100%);
}
#content.appear{
  visibility: visible;
  opacity: 1;
          transform: translateX(0);
  -webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
_x000D_
_x000D_

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

PHP - check if variable is undefined

To check is variable is set you need to use isset function.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

this code will print:

isset true
isset false

read more in https://php.net/manual/en/function.isset.php

Formatting Phone Numbers in PHP

This is a US phone formatter that works on more versions of numbers than any of the current answers.

$numbers = explode("\n", '(111) 222-3333
((111) 222-3333
1112223333
111 222-3333
111-222-3333
(111)2223333
+11234567890
    1-8002353551
    123-456-7890   -Hello!
+1 - 1234567890 
');


foreach($numbers as $number)
{
    print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
}

And here is a breakdown of the regex:

Cell: +1 999-(555 0001)

.*          zero or more of anything "Cell: +1 "
(\d{3})     three digits "999"
[^\d]{0,7}  zero or up to 7 of something not a digit "-("
(\d{3})     three digits "555"
[^\d]{0,7}  zero or up to 7 of something not a digit " "
(\d{4})     four digits "0001"
.*          zero or more of anything ")"

Updated: March 11, 2015 to use {0,7} instead of {,7}

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

From documentation: https://docs.djangoproject.com/en/1.10/ref/settings/

if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”.

And from here: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS

I am using something like this:

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'www.mysite.com']

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

for each project in your solution make sure that

Properties > Config. Properties > General > Platform Toolset

is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012

you also may be working on v100 from visual studio 2012

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

How do I detect when someone shakes an iPhone?

This is the basic delegate code you need:

#define kAccelerationThreshold      2.2

#pragma mark -
#pragma mark UIAccelerometerDelegate Methods
    - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
    {   
        if (fabsf(acceleration.x) > kAccelerationThreshold || fabsf(acceleration.y) > kAccelerationThreshold || fabsf(acceleration.z) > kAccelerationThreshold) 
            [self myShakeMethodGoesHere];   
    }

Also set the in the appropriate code in the Interface. i.e:

@interface MyViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UIAccelerometerDelegate>

How to get elements with multiple classes

querySelectorAll with standard class selectors also works for this.

document.querySelectorAll('.class1.class2');

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

use context.Database.BeginTransaction.

From MSDN:

using (var context = new BloggingContext()) 
{ 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
        try 
        { 
            context.Database.ExecuteSqlCommand( 
                @"UPDATE Blogs SET Rating = 5" + 
                    " WHERE Name LIKE '%Entity Framework%'" 
                ); 

            var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
            foreach (var post in query) 
            { 
                post.Title += "[Cool Blog]"; 
            } 

            context.SaveChanges(); 

            dbContextTransaction.Commit(); 
        } 
        catch (Exception) 
        { 
            dbContextTransaction.Rollback(); //Required according to MSDN article 
            throw; //Not in MSDN article, but recommended so the exception still bubbles up
        } 
    } 
} 

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

How to get a password from a shell script without echoing

Turn echo off using stty, then back on again after.

Google Spreadsheet, Count IF contains a string

Wildcards worked for me when the string I was searching for could be entered manually. However, I wanted to store this string in another cell and refer to it. I couldn't figure out how to do this with wildcards so I ended up doing the following:

A1 is the cell containing my search string. B and C are the columns within which I want to count the number of instances of A1, including within strings:

=COUNTIF(ARRAYFORMULA(ISNUMBER(SEARCH(A1, B:C))), TRUE)

add maven repository to build.gradle

Add the maven repository outside the buildscript configuration block of your main build.gradle file as follows:

repositories {
        maven {
            url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases"
        }
    }

Make sure that you add them after the following:

apply plugin: 'com.android.application'

How to change python version in anaconda spyder

You can launch the correct version of Spyder by launching from Ananconda's Navigator. From the dropdown, switch to your desired environment and then press the launch Spyder button. You should be able to check the results right away.

Requested bean is currently in creation: Is there an unresolvable circular reference?

I think you could use Spring's

@Lazy

annotation on one of the autowired fields to break circular dependency.

I'm not sure if this works/exists in mentioned Spring version.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

Onclick javascript to make browser go back to previous page?

the only one that worked for me:

function goBackAndRefresh() {
  window.history.go(-1);
  setTimeout(() => {
    location.reload();
  }, 0);
}