Programs & Examples On #Onpreinit

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

Reset Entity-Framework Migrations

UPDATE 2020 => Reset Entity-Framework Migrations

Add-Migration Initial -Context ApplicationDbContext

ApplicationDbContext => Your context.

But if you need only update a identity schema existent, try it: https://stackoverflow.com/a/59966100/4654957

LD_LIBRARY_PATH vs LIBRARY_PATH

LD_LIBRARY_PATH is searched when the program starts, LIBRARY_PATH is searched at link time.

caveat from comments:

SQL to Entity Framework Count Group-By

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

The data-toggle attributes in Twitter Bootstrap

Here you can also find more examples for values that data-toggle can have assigned. Just visit the page and then CTRL+F to search for data-toggle.

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

Python: Figure out local timezone

The following appears to work for 3.7+, using standard libs:

from datetime import timedelta
from datetime import timezone
import time

def currenttz():
    if time.daylight:
        return timezone(timedelta(seconds=-time.altzone),time.tzname[1])
    else:
        return timezone(timedelta(seconds=-time.timezone),time.tzname[0])

Send string to stdin

You can also use read like this

echo "enter your name"
read name
echo $name

How do I delete all the duplicate records in a MySQL table without temp tables

An alternative way would be to create a new temporary table with same structure.

CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0

Then create the primary key in the table.

ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)

Finally copy all records from the original table while ignoring the duplicate records.

INSERT IGNORE INTO temp_table AS SELECT * FROM original_table

Now you can delete the original table and rename the new table.

DROP TABLE original_table
RENAME TABLE temp_table TO original_table

How to redirect a URL path in IIS?

If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.

http://www.isapirewrite.com/docs/

It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.

Is it possible to use pip to install a package from a private GitHub repository?

I figured out a way to automagically 'pip install' a GitLab private repository that requires no password prompt. This approach uses GitLab "Deploy Keys" and an SSH configuration file, so you can deploy using keys other than your personal SSH keys (in my case, for use by a 'bot). Perhaps someone kind soul can verify using GitHub.

Create a New SSH key:

ssh-keygen -t rsa -C "GitLab_Robot_Deploy_Key"

The file should show up as ~/.ssh/GitLab_Robot_Deploy_Key and ~/.ssh/GitLab_Robot_Deploy_Key.pub.

Copy and paste the contents of the ~/.ssh/GitLab_Robot_Deploy_Key.pub file into the GitLab "Deploy Keys" dialog.

Test the New Deploy Key

The following command tells SSH to use your new deploy key to set up the connection. On success, you should get the message: "Welcome to GitLab, UserName!"

ssh -T -i ~/.ssh/GitLab_Robot_Deploy_Key [email protected]

Create the SSH Configuration File

Next, use an editor to create a ~/.ssh/config file. Add the following contents. The 'Host' value can be anything you want (just remember it, because you'll be using it later). The HostName is the URL to your GitLab instance. The IdentifyFile is path to the SSH key file you created in the first step.

Host GitLab
  HostName gitlab.mycorp.com
  IdentityFile ~/.ssh/GitLab_Robot_Deploy_Key

Point SSH to the Configuration file

oxyum gave us the recipe for using pip with SSH:

pip install git+ssh://[email protected]/my_name/my_repo.git

We just need to modify it a bit to make SSH use our new Deploy Key. We do that by pointing SSH to the Host entry in the SSH configuration file. Just replace the 'gitlab.mycorp.com' in the command to the host name we used in the SSH configuration file:

pip install git+ssh://git@GitLab/my_name/my_repo.git

The package should now install without any password prompt.

Reference A
Reference B

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

Copy the DLL to C:\Windows\SysWoW64\
In an elevated command prompt: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

Copy the DLL to C:\Windows\System32\
In an elevated command prompt: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

I know it seems the wrong way round, but that's the way it works. See:

http://support.microsoft.com/kb/249873
Quote: "Note On a 64-bit version of a Windows operating system, there are two versions of the Regsv32.exe file:
The 64-bit version is %systemroot%\System32\regsvr32.exe.
The 32-bit version is %systemroot%\SysWoW64\regsvr32.exe.
"

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

In android studio add/change this line at the end of gradle.properties (Global Properties):

...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m 

if it doesn't work you can retry with bigger than 1024 heap size.

RS256 vs HS256: What's the difference?

In cryptography there are two types of algorithms used:

Symmetric algorithms

A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".

Asymmetric algorithms

Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.

HS256 and RS256 Scenario

These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.

HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.

RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.

ASP.NET MVC controller actions that return JSON or partial html

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Method from the jquery getJSON method by simply...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

Declare and Initialize String Array in VBA

In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:

Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")

This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.

How to pass a null variable to a SQL Stored Procedure from C#.net code

Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

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

Add a property to keep track of the selected cell

@property (nonatomic) int currentSelection;

Set it to a sentinel value in (for example) viewDidLoad, to make sure that the UITableView starts in the 'normal' position

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //sentinel
    self.currentSelection = -1;
}

In heightForRowAtIndexPath you can set the height you want for the selected cell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int rowHeight;
    if ([indexPath row] == self.currentSelection) {
        rowHeight = self.newCellHeight;
    } else rowHeight = 57.0f;
    return rowHeight;
}

In didSelectRowAtIndexPath you save the current selection and save a dynamic height, if required

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        // do things with your cell here

        // set selection
        self.currentSelection = indexPath.row;
        // save height for full text label
        self.newCellHeight = cell.titleLbl.frame.size.height + cell.descriptionLbl.frame.size.height + 10;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

In didDeselectRowAtIndexPath set the selection index back to the sentinel value and animate the cell back to normal form

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {       
        // do things with your cell here

        // sentinel
        self.currentSelection = -1;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

Bash tool to get nth line from a file

You can also use Perl for this:

perl -wnl -e '$.== NUM && print && exit;' some.file

How to install Hibernate Tools in Eclipse?

Since it is for Ganymede (eclipse 3.4), I would advise to uncompress the zip in the dropins in the HibernateTools-3.2.4.Beta1-R20081031133 directory created after the name of the archive.

Once it is done, create in the [eclipse\dropins\HibernateTools-3.2.4.Beta1-R20081031133] an 'eclipse' directory, in which you will move the plugins and features directories creating at the extraction of the files of the archive.

Add a .exclipseextension in [eclipse\dropins\HibernateTools-3.2.4.Beta1-R20081031133\eclipse]:

name=QuickRex
id=org.hibernate.eclipse
version=3.2.4b1

So:

eclipse
    dropins
         HibernateTools-3.2.4.Beta1-R20081031133
             eclipse
                 .eclipseextension
                 features
                 plugins

Relaunch eclipse and the plugin Hibernate should be detected.

If you install another eclipse, just copy the content of your dropins directory to the new eclipse\dropins and your set of plugins will be detected again.

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

Bat file to run a .exe at the command prompt

Just put that line in the bat file...

Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.

How to remove specific value from array using jQuery

I'd extend the Array class with a pick_and_remove() function, like so:

var ArrayInstanceExtensions = {
    pick_and_remove: function(index){
        var picked_element = this[index];
        this.splice(index,1);
        return picked_element;
    } 
};
$.extend(Array.prototype, ArrayInstanceExtensions);

While it may seem a bit verbose, you can now call pick_and_remove() on any array you possibly want!

Usage:

array = [4,5,6]           //=> [4,5,6]
array.pick_and_remove(1); //=> 5
array;                    //=> [4,6]

You can see all of this in pokemon-themed action here.

git clone through ssh

I want to attempt an answer that includes git-flow, and three 'points' or use-cases, the git central repository, the local development and the production machine. This is not well tested.

I am giving incredibly specific commands. Instead of saying <your folder>, I will say /root/git. The only place where I am changing the original command is replacing my specific server name with example.com. I will explain the folders purpose is so you can adjust it accordingly. Please let me know of any confusion and I will update the answer.

The git version on the server is 1.7.1. The server is CentOS 6.3 (Final).

The git version on the development machine is 1.8.1.1. This is Mac OS X 10.8.4.

The central repository and the production machine are on the same machine.

the central repository, which svn users can related to as 'server' is configured as follows. I have a folder /root/git where I keep all my git repositories. I want to create a git repository for a project I call 'flowers'.

cd /root/git
git clone --bare flowers flowers.git

The git command gave two messages:

Initialized empty Git repository in /root/git/flowers.git/
warning: You appear to have cloned an empty repository.

Nothing to worry about.

On the development machine is configured as follows. I have a folder /home/kinjal/Sites where I put all my projects. I now want to get the central git repository.

cd /home/kinjal/Sites
git clone [email protected]:/root/git/flowers.git

This gets me to a point where I can start adding stuff to it. I first set up git flow

git flow init -d

By default this is on branch develop. I add my code here, now. Then I need to commit to the central git repository.

git add .
git commit -am 'initial'
git push

At this point it pushed to the develop branch. I want to also add this to the master branch.

git flow release start v0.0.0 develop
git flow release finish v0.0.0
git push

Note that I did nothing between the release start and release finish. And when I did the release finish I was prompted to edit two files. This pushed the develop branch to master.

On the production site, which is on the same machine as my central git repository, I want put the repository in /var/www/vhosts/example.net. I already have /var/www/vhosts.

cd /var/www/vhosts
git clone file:///root/git/flowers.git example.net

If the production machine would also be on a different machine, the git clone command would look like the one used on the development machine.

Gradle failed to resolve library in Android Studio

Well, it's co.lemonlabs, you have a typo in your build.gradle:

compile 'co.lemonlabs:expandable-button-menu:1.0.0'

Source: https://github.com/lemonlabs/ExpandableButtonMenu#including-in-your-project

How to convert Rows to Columns in Oracle?

You can do it with a pivot query, like this:

select * from (
   select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
   from my_table t
)
pivot 
(
   MIN(DOCUMENT_ID)
   for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)

Here is a demo on sqlfiddle.com.

Casting a number to a string in TypeScript

Just utilize toString or toLocaleString I'd say. So:

var page_number:number = 3;
window.location.hash = page_number.toLocaleString();

These throw an error if page_number is null or undefined. If you don't want that you can choose the fix appropriate for your situation:

// Fix 1:
window.location.hash = (page_number || 1).toLocaleString();

// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toLocaleString();

// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();

Ripple effect on Android Lollipop CardView

Add the following to your xml:

android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground"

And add to your adapter (if it's your case)

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val attrs = intArrayOf(R.attr.selectableItemBackground)
            val typedArray = holder.itemView.context.obtainStyledAttributes(attrs)
            val selectableItemBackground = typedArray.getResourceId(0, 0)
            typedArray.recycle()

            holder.itemView.isClickable = true
            holder.itemView.isFocusable = true
            holder.itemView.foreground = holder.itemView.context.getDrawable(selectableItemBackground)
        }
    }

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Why use String.Format?

Several reasons:

  1. String.Format() is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.
  2. You can do some powerful things by putting format strings in configuration files.
  3. String.Format() is often faster, as it uses a StringBuilder and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.
  4. String.Format() is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf() function.

Finally, don't forget StringBuilder.AppendFormat(). String.Format() actually uses this method behind the scenes*, and going to the StringBuilder directly can give you a kind of hybrid approach: explicitly use .Append() (analogous to concatenation) for some parts of a large string, and use .AppendFormat() in others.


* [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.

syntax error: unexpected token <

The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.

In this case, it expects to find a { (start of JSON); instead it finds a < (start of a heading element).

Successful response:

<html>
  <head></head>
  <body>
    {"foo": "bar", "baz": "qux"}
  </body>
</html>

Not-found response:

<html>
  <head></head>
  <body>
    <h1>Not Found</h1>
    <p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
  </body>
</html>

Try visiting the data endpoint's URL in your browser to see what's returned.

How to catch a unique constraint error in a PL/SQL block?

As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */ in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.

Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME which has a unique constraint on a column called IDX_COL_NAME.

INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */ 
INTO TABLE_NAME(
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n)
SELECT 
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n);

This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.

Get current domain

I know this might not be entirely on the subject, but in my experience, I find storing WWW-ness of current URL in a variable useful.

Edit: In addition, please see my comment below, to see what this is getting at.

This is important when determining whether to dispatch Ajax calls with "www", or without:

$.ajax("url" : "www.site.com/script.php", ...

$.ajax("url" : "site.com/script.php", ...

When dispatching an Ajax call the domain name must match that of in the browser's address bar, otherwise you will have Uncaught SecurityError in console.

So I came up with this solution to address the issue:

<?php
    substr($_SERVER['SERVER_NAME'], 0, 3) == "www" ? $WWW = true : $WWW = false;

    if ($WWW) {
        /* We have www.example.com */
    } else {
        /* We have example.com */
    }
?>

Then, based on whether $WWW is true, or false run the proper Ajax call.

I know this might sound trivial, but this is such a common problem that is easy to trip over.

Git merge with force overwrite

These commands will help in overwriting code of demo branch into master

git fetch --all

Pull Your demo branch on local

git pull origin demo

Now checkout to master branch. This branch will be completely changed with the code on demo branch

git checkout master

Stay in the master branch and run this command.

git reset --hard origin/demo

reset means you will be resetting current branch

--hard is a flag that means it will be reset without raising any merge conflict

origin/demo will be the branch that will be considered to be the code that will forcefully overwrite current master branch

The output of the above command will show you your last commit message on origin/demo or demo branch enter image description here

Then, in the end, force push the code on the master branch to your remote repo.

git push --force

How to test code dependent on environment variables using JUnit?

One slow, dependable, old-school method that always works in every operating system with every language (and even between languages) is to write the "system/environment" data you need to a temporary text file, read it when you need it, and then erase it. Of course, if you're running in parallel, then you need unique names for the file, and if you're putting sensitive information in it, then you need to encrypt it.

How to add a new row to an empty numpy array

I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.

x = np.empty((0,3))
y = np.array([1,2,3])
for i in ...
    x = np.vstack((x,y))

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
Out[31]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?


Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

What possibilities can cause "Service Unavailable 503" error?

We recently encountered this error, root cause turned out to be an expired SSL cert on the IIS server. The Load Balancer (infront of our web tier) found the SSL expired, and instead of handling the HTTP traffic over to one of the IIS servers, started showing this error. So basically IIS unable to server requests, for a totally different reason :)

How to make HTTP Post request with JSON body in Swift

    // prepare json data
    let mapDict = [ "1":"First", "2":"Second"]

    let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
    let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData

    // create post request
    let url = NSURL(string: "http://httpbin.org/post")!
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"

    // insert json data to the request
    request.httpBody = jsonData as Data


    let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
            return
        }
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

            print("Result",result!)

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()

How to trigger the window resize event in JavaScript?

Response with RxJS

Say Like something in Angular

size$: Observable<number> = fromEvent(window, 'resize').pipe(
            debounceTime(250),
            throttleTime(300),
            mergeMap(() => of(document.body.clientHeight)),
            distinctUntilChanged(),
            startWith(document.body.clientHeight),
          );

If manual subscription desired (Or Not Angular)

this.size$.subscribe((g) => {
      console.log('clientHeight', g);
    })

Since my intial startWith Value might be incorrect (dispatch for correction)

window.dispatchEvent(new Event('resize'));

In say Angular (I could..)

<div class="iframe-container"  [style.height.px]="size$ | async" >..

Traversing text in Insert mode

I believe Home and End (and PageUp/PageDn) also work normally while in insert mode, but aside from that, I don't believe there are any other standard keys defined for text traversal.

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

How to enable mod_rewrite for Apache 2.2

For my situation, I had

RewriteEngine On

in my .htaccess, along with the module being loaded, and it was not working.

The solution to my problem was to edit my vhost entry to inlcude

AllowOverride all

in the <Directory> section for the site in question.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

Max parallel http connections in a browser?

My understanding is that the connection limit is not changeable on the client side. The connection limit must be changed on the server to have any effect. By default, many servers will only allow 2 connections per unique client.

The client is not the browser, it is the client machine issuing the TCP/IP requests.

To see the effect very clearly, use something like JMeter to fire off a bunch of web service calls to your server host - it will accept the first two and will not accept another until one of the two is completed. The amazing thing about this is that for a SOA shop, this is critical, yet hardly anyone is really aware of it.

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

How to add a button dynamically in Android?

If you want to add dynamically buttons try this:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    for (int i = 1; i <= 5; i++) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
        layout.setOrientation(LinearLayout.VERTICAL);
        Button btn = new Button(this);
        btn.setText("    ");
        layout.addView(btn);
    }

}

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

How can I declare enums using java

public enum MyEnum {
   ONE(1),
   TWO(2);
   private int value;
   private MyEnum(int value) {
      this.value = value;
   }
   public int getValue() {
      return value;
   }
}

In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)

As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.

Update: For strings the only difference is that your constructor argument is String, and you declare enums with TEST("test")

How to populate HTML dropdown list with values from database

<select name="owner">
<?php 
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

Checking if object is empty, works with ng-show but not from controller?

Or, if using lo-dash: _.empty(value).

"Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects with no own enumerable properties are considered "empty"."

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

How to find Google's IP address?

The following IP address ranges belong to Google:

64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.64.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255

Like many popular Web sites, Google utilizes multiple Internet servers to handle incoming requests to its Web site. Instead of entering http://www.google.com/ into the browser, a person can enter http:// followed by one of the above addresses, for example:

http://74.125.224.72/

SOURCE

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

Iterating over a 2 dimensional python list

>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

Ajax Success and Error function failure

I was having the same issue and fixed it by simply adding a dataType = "text" line to my ajax call. Make the dataType match the response you expect to get back from the server (your "insert successful" or "something went wrong" error message).

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

How do I create HTML table using jQuery dynamically?

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

AppSettings get value from .config file

Give this a go:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

Auto-refreshing div with jQuery - setTimeout or another method?

$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  setInterval(function() {
    $('#notice_div').load('response.php');
  }, 3000); // the "3000" 
});

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Fetch first element which matches criteria

I think this is the best way:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);

Git Push Error: insufficient permission for adding an object to repository database

The sumplest solution is:

From the project dir:

sudo chmod 777 -R .git/objects

What's the difference between a word and byte?

If a machine is byte-addressable and a word is the smallest unit that can be addressed on memory then I guess a word would be a byte!

Error using eclipse for Android - No resource found that matches the given name

Accidentally moved the "values" folder outside of the "res" folder. Moved it back and it fired up!

How to convert a String to JsonObject using gson library

String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.

How to jQuery clone() and change id?

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO

Code:

   var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter('[id^=id]:last') 
           //            ^-- Use '#id' if you want to insert the cloned 
           //                element in the beginning
          .text('Cloned ' + (cloneCount-1)); //<--For DEMO
   }); 

Try,

$("#id").clone().attr('id', 'id1').after("#id");

If you want a automatic counter, then see below,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 

VHDL - How should I create a clock in a testbench?

If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:

library ieee;
use ieee.std_logic_1164.all;

entity tb is
end entity;

architecture sim of tb is

  -- Procedure for clock generation
  procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
    constant PERIOD    : time := 1 sec / FREQ;        -- Full period
    constant HIGH_TIME : time := PERIOD / 2;          -- High time
    constant LOW_TIME  : time := PERIOD - HIGH_TIME;  -- Low time; always >= HIGH_TIME
  begin
    -- Check the arguments
    assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
    -- Generate a clock cycle
    loop
      clk <= '1';
      wait for HIGH_TIME;
      clk <= '0';
      wait for LOW_TIME;
    end loop;
  end procedure;

  -- Clock frequency and signal
  signal clk_166 : std_logic;
  signal clk_125 : std_logic;

begin

  -- Clock generation with concurrent procedure call
  clk_gen(clk_166, 166.667E6);  -- 166.667 MHz clock
  clk_gen(clk_125, 125.000E6);  -- 125.000 MHz clock

  -- Time resolution show
  assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;

end architecture;

The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.

If the clk_gen procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.

Waveform for clocks are shown in figure below.

Waveforms for clk_166 and clk_125

An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:

-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
  constant HIGH_TIME   : time := 0.5 sec / FREQ;  -- High time as fixed value
  variable low_time_v  : time;                    -- Low time calculated per cycle; always >= HIGH_TIME
  variable cycles_v    : real := 0.0;             -- Number of cycles
  variable freq_time_v : time := 0 fs;            -- Time used for generation of cycles
begin
  -- Check the arguments
  assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
  -- Initial phase shift
  clk <= '0';
  wait for PHASE;
  -- Generate cycles
  loop
    -- Only high pulse if run is '1' or 'H'
    if (run = '1') or (run = 'H') then
      clk <= run;
    end if;
    wait for HIGH_TIME;
    -- Low part of cycle
    clk <= '0';
    low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME;  -- + 1.0 for cycle after current
    wait for low_time_v;
    -- Cycle counter and time passed update
    cycles_v := cycles_v + 1.0;
    freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
  end loop;
end procedure;

Again reuse through a package will be nice.

Firebug like plugin for Safari browser

Firebug lite plugin in Safari extensions didn't work (it's made by slicefactory, I don't think it's offical). btw, #2 works for me!

Accessing @attribute from SimpleXML

$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;

$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]

Use SimpleXMLElement::attributes.

Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "@attributes", so you can't do $sxml->elem->{"@attributes"}["attrib"].

PowerShell: Store Entire Text File Contents in Variable

To get the entire contents of a file:

$content = [IO.File]::ReadAllText(".\test.txt")

Number of lines:

([IO.File]::ReadAllLines(".\test.txt")).length

or

(gc .\test.ps1).length

Sort of hackish to include trailing empty line:

[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count

NSCameraUsageDescription in iOS 10.0 runtime crash?

Another instance that I faced while trying to use the camera, was that it was still busy crashing giving same _CRASHING_DUE_TO_PRIVACY even after adding the "Camera Usage Description". After failing to get anything tangible from the call stack, switched to the "Organizer" and looked into the crash reports on the device. I found that it was in fact complaining about the privacy due to the missing "Microphone Usage Description". I added that and got rid of such a cryptic break down.

Windows command to convert Unix line endings?

I cloned my git project using the git bash on windows. All the files then had LF endings. Our repository has CRLF endings as default.

I deleted the project, and then cloned it again using the Windows Command Prompt. The CRLF endings were intact then. In my case, if I had changed the endings for the project, then it would've resulted in a huge commit and would've caused trouble for my teammates. So, did it this way. Hope this helps somebody.

What exactly do "u" and "r" string flags do, and what are raw string literals?

There are two types of string in python: the traditional str type and the newer unicode type. If you type a string literal without the u in front you get the old str type which stores 8-bit characters, and with the u in front you get the newer unicode type that can store any Unicode character.

The r doesn't change the type at all, it just changes how the string literal is interpreted. Without the r, backslashes are treated as escape characters. With the r, backslashes are treated as literal. Either way, the type is the same.

ur is of course a Unicode string where backslashes are literal backslashes, not part of escape codes.

You can try to convert a Unicode string to an old string using the str() function, but if there are any unicode characters that cannot be represented in the old string, you will get an exception. You could replace them with question marks first if you wish, but of course this would cause those characters to be unreadable. It is not recommended to use the str type if you want to correctly handle unicode characters.

How to get error message when ifstream open fails

The std::system_error example above is slightly incorrect. std::system_category() will map the error codes from system's native error code facility. For *nix, this is errno. For Win32, it is GetLastError(). ie, on Windows, the above example will print

failed to open C:\path\to\forbidden: The data is invalid

because EACCES is 13 which is the Win32 error code ERROR_INVALID_DATA

To fix it, either use the system's native error code facility, eg on Win32

throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);

Or use errno and std::generic_category(), eg

throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);

How do I start Mongo DB from Windows?

Step 1: First download the .msi i.e is the installation file from

https://www.mongodb.org/downloads#production

Step 2: Perform the installation using the so downloaded .msi file.Automatically it gets stored in program files. You could perform a custom installation and change the directory.

After this you should be able to see a Mongodb folder

Step 3: Create a new folder in this Mongodb folder with name 'data'. Create another new folder in your data directory with the name 'db'.

Step 4: Open cmd. Go to the directory where your mongodb folder exists and go to a path like C:\MongoDB\Server\3.0\bin. In the bin folder you should have mongodb.exe

Step 5: Now use

mongod --port 27017 --dbpath "C:\MongoDB\data\db"

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

HttpUtility does not exist in the current context

In order to resolve this, Kindly go to the below path

Project-->Properties-->Application-->TargetFramework

and change the Framework to ".NET Framework 4".

Once you do this, the project will close and re-open.

This should solve the error

(but for some reason @Karan Modi's answer does not...)

next right-click the references tab in the solution explorer and choose add reference,

choose "System.Web"

(declaring the namespace directly by "using System.Web;" doesnt seems to be enough...you have to add it to the solution explorer...i cant understand why - which is no surprise because i am a cobol programmer..

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

Validating a Textbox field for only numeric input.

I know this is an old question but I figured out I should pitch my answer anyways.

The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.

using System;

private bool ValidateText(string text){
    char[] characters = text.ToCharArray();

    foreach(char c in characters){
        if(!char.IsNumber(c))
            return false;
    }
    return true;
}

jQuery Show-Hide DIV based on Checkbox Value

A tip to all people that use flat-red, flat-green plugin, because of this plugin the answers above wont work!

In that case, use onchange="do_your_stuff();" on the label, for example: Your checkbox here

The reason why it doesn't work is that this Jquery creates a lot of objects around the real checkbox, so you can't see if it's changed or not.

But if someone click straight on checkbox, won't work :'(

jQuery to serialize only elements within a div

What about my solution:

function serializeDiv( $div, serialize_method )
{
    // Accepts 'serialize', 'serializeArray'; Implicit 'serialize'
    serialize_method = serialize_method || 'serialize';

    // Unique selector for wrapper forms
    var inner_wrapper_class = 'any_unique_class_for_wrapped_content';

    // Wrap content with a form
    $div.wrapInner( "<form class='"+inner_wrapper_class+"'></form>" );

    // Serialize inputs
    var result = $('.'+inner_wrapper_class, $div)[serialize_method]();

    // Eliminate newly created form
    $('.script_wrap_inner_div_form', $div).contents().unwrap();

    // Return result
    return result;
}

/* USE: */

// For: $('#div').serialize()
serializeDiv($('#div')); /* or */ serializeDiv($('#div'), 'serialize');

// For: $('#div').serializeArray()
serializeDiv($('#div'), 'serializeArray');

_x000D_
_x000D_
function serializeDiv( $div, serialize_method )_x000D_
{_x000D_
 // Accepts 'serialize', 'serializeArray'; Implicit 'serialize'_x000D_
 serialize_method = serialize_method || 'serialize';_x000D_
_x000D_
 // Unique selector for wrapper forms_x000D_
 var inner_wrapper_class = 'any_unique_class_for_wrapped_content';_x000D_
_x000D_
 // Wrap content with a form_x000D_
 $div.wrapInner( "<form class='"+inner_wrapper_class+"'></form>" );_x000D_
_x000D_
 // Serialize inputs_x000D_
 var result = $('.'+inner_wrapper_class, $div)[serialize_method]();_x000D_
_x000D_
 // Eliminate newly created form_x000D_
 $('.script_wrap_inner_div_form', $div).contents().unwrap();_x000D_
_x000D_
 // Return result_x000D_
 return result;_x000D_
}_x000D_
_x000D_
/* USE: */_x000D_
_x000D_
var r = serializeDiv($('#div')); /* or serializeDiv($('#div'), 'serialize'); */_x000D_
console.log("For: $('#div').serialize()");_x000D_
console.log(r);_x000D_
_x000D_
var r = serializeDiv($('#div'), 'serializeArray');_x000D_
console.log("For: $('#div').serializeArray()");_x000D_
console.log(r);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="div">_x000D_
  <input name="input1" value="input1_value">_x000D_
  <textarea name="textarea1">textarea_value</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to format JSON in notepad++

Try with JSToolNpp and follow the snap like this then Plugins | JSTool | JSFormat.

enter image description here

how to check if List<T> element contains an item with a Particular Property Value

If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex instance method. Such as

int index = list.FindIndex(f => f.Bar == 17);

Where f => f.Bar == 17 is a predicate with the matching criteria.

In your case you might write

int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0) 
{
    // element exists, do what you need
}

Send response to all clients except sender

For namespaces within rooms looping the list of clients in a room (similar to Nav's answer) is one of only two approaches I've found that will work. The other is to use exclude. E.G.

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

require(vendor/autoload.php): failed to open stream

First make sure you have installed the composer.

composer install

If you already have installed then update the composer.

composer update

Node.js check if file exists

After a bit of experimentation, I found the following example using fs.stat to be a good way to asynchronously check whether a file exists. It also checks that your "file" is "really-is-a-file" (and not a directory).

This method uses Promises, assuming that you are working with an asynchronous codebase:

const fileExists = path => {
  return new Promise((resolve, reject) => {
    try {
      fs.stat(path, (error, file) => {
        if (!error && file.isFile()) {
          return resolve(true);
        }

        if (error && error.code === 'ENOENT') {
          return resolve(false);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
};

If the file does not exist, the promise still resolves, albeit false. If the file does exist, and it is a directory, then is resolves true. Any errors attempting to read the file will reject the promise the error itself.

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Before resetting the emulator first go to your projects "project navigator" screen and under the general -> depoyment info screen check that the main interface property is properly setup!

enter image description here

Browse and display files in a git repo without cloning

Take a look at http://git-scm.com/book/en/Git-Internals-Transfer-Protocols for info on how to do this over some transport protocols. Note this won't work for standard git over SSH.

For git over SSH, an up-to-date server-side git should allow you to git-archive directly from the remote, which you could then e.g. pipe to "tar t" to get a list of all files in a given commit.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Incase you don't want to use nextint, you can also use buffered reader, where using inputstream and readline function read the string.

Convert Pandas Series to DateTime in a DataFrame

You can't: DataFrame columns are Series, by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs):

>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205  76032930   2015-01-24 00:05:27.513000
232  76032930   2015-01-24 00:06:46.703000
233  76032930   2015-01-24 00:06:56.707000
413  76032930   2015-01-24 00:14:24.957000
565  76032930   2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205  76032930    1
232  76032930    1
233  76032930    1
413  76032930    1
565  76032930    1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205  76032930     5
232  76032930     6
233  76032930     6
413  76032930    14
565  76032930    23
dtype: int64

If you're stuck using an older version of pandas, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:

>>> df["TimeReviewed"].apply(lambda x: x.year)
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
Name: TimeReviewed, dtype: int64

Oracle: how to UPSERT (update or insert into a table?)

From http://www.praetoriate.com/oracle_tips_upserts.htm:

"In Oracle9i, an UPSERT can accomplish this task in a single statement:"

INSERT
FIRST WHEN
   credit_limit >=100000
THEN INTO
   rich_customers
VALUES(cust_id,cust_credit_limit)
   INTO customers
ELSE
   INTO customers SELECT * FROM new_customers;

Create a SQL query to retrieve most recent records

The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:

WITH UserStatus (User, Date, Status, Notes, Ord)
as
(
SELECT Date, User, Status, Notes, 
     ROW_NUMBER() OVER (PARTITION BY User ORDER BY Date DESC)
FROM [SOMETABLE]
)

SELECT User, Date, Status, Notes from UserStatus where Ord = 1

This would also facilitate the display of the most recent x statuses from each user.

How to get DataGridView cell value in messagebox?

MessageBox.Show(" Value at 0,0" + DataGridView1.Rows[0].Cells[0].Value );

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

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

I had a similar issue with mongoose :

fields: 
    [ '[object Object]',
     '[object Object]',
     '[object Object]',
     '[object Object]' ] }

In fact, I was using "type" as a property name in my schema :

fields: [
    {
      name: String,
      type: {
        type: String
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

To avoid that behavior, you have to change the parameter to :

fields: [
    {
      name: String,
      type: {
        type: { type: String }
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs.

So I solved my problem like this:

# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`

test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH

Et voilà !

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

Getting scroll bar width using JavaScript

// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

View markdown files offline

You may use Scribefire Next.

It's a Mozilla Firefox browser plugin. Just install the extension and fire up Firefox. Customize your toolbar and place the Scribefire shortcut to it. And since it's a browser plugin, you can use it in Mac, Linux and Windows.

When you want to write in Markdown mode, just click Edit Code from the Scribefire window.

Now to meet your purpose, go to Edit Code mode and copy all the texts and paste it to your .md file and upload.

There is no live preview feature for this, you have to toggle Edit Code and Edit Visually to preview your text.

I'm using it in my Linux Mint box:

enter image description here

enter image description here

Update:

It's year 2014, need to add some other awesome tool here for other readers and researchers. Just recently used Brackets + Markdown Preview Extension.

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

Is there a /dev/null on Windows?

Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).

Here is another:

Should I declare Jackson's ObjectMapper as a static field?

Although ObjectMapper is thread safe, I would strongly discourage from declaring it as a static variable, especially in multithreaded application. Not even because it is a bad practice, but because you are running a heavy risk of deadlocking. I am telling it from my own experience. I created an application with 4 identical threads that were getting and processing JSON data from web services. My application was frequently stalling on the following command, according to the thread dump:

Map aPage = mapper.readValue(reader, Map.class);

Beside that, performance was not good. When I replaced static variable with the instance based variable, stalling disappeared and performance quadrupled. I.e. 2.4 millions JSON documents were processed in 40min.56sec., instead of 2.5 hours previously.

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

Rails: How can I rename a database column in a Ruby on Rails migration?

In my opinion, in this case, it's better to use rake db:rollback, then edit your migration and again run rake db:migrate.

However, if you have data in the column you don't want to lose, then use rename_column.

How to convert a Java 8 Stream to an Array?

Convert text to string array where separating each value by comma, and trim every field, for example:

String[] stringArray = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);

Use JAXB to create Object from XML String

Or if you want a simple one-liner:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

SQL Server PRINT SELECT (Print a select query result)?

You know, there might be an easier way but the first thing that pops to mind is:

Declare @SumVal int;
Select @SumVal=Sum(Amount) From Expense;
Print @SumVal;

You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

How does the "position: sticky;" property work?

I had to use the following CSS to get it working:

.parent {
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
    overflow: visible;
}

.sticky {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
}

If above dosen't work then...

Go through all ancestors and make sure none of these elements have overflow: hidden. You have to change this to overflow: visible

Return list of items in list greater than some value

A list comprehension is a simple approach:

j2 = [x for x in j if x >= 5]

Alternately, you can use filter for the exact same result:

j2 = filter(lambda x: x >= 5, j)

Note that the original list j is unmodified.

What is the => assignment in C# in a property signature

What you're looking at is an expression-bodied member not a lambda expression.

When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:

public int MaxHealth
{
    get
    {
        return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
    }
}

(You can verify this for yourself by pumping the code into a tool called TryRoslyn.)

Expression-bodied members - like most C# 6 features - are just syntactic sugar. This means that they don’t provide functionality that couldn't otherwise be achieved through existing features. Instead, these new features allow a more expressive and succinct syntax to be used

As you can see, expression-bodied members have a handful of shortcuts that make property members more compact:

  • There is no need to use a return statement because the compiler can infer that you want to return the result of the expression
  • There is no need to create a statement block because the body is only one expression
  • There is no need to use the get keyword because it is implied by the use of the expression-bodied member syntax.

I have made the final point bold because it is relevant to your actual question, which I will answer now.

The difference between...

// expression-bodied member property
public int MaxHealth => x ? y:z;

And...

// field with field initializer
public int MaxHealth = x ? y:z;

Is the same as the difference between...

public int MaxHealth
{
    get
    {
        return x ? y:z;
    }
}

And...

public int MaxHealth = x ? y:z;

Which - if you understand properties - should be obvious.

Just to be clear, though: the first listing is a property with a getter under the hood that will be called each time you access it. The second listing is is a field with a field initializer, whose expression is only evaluated once, when the type is instantiated.

This difference in syntax is actually quite subtle and can lead to a "gotcha" which is described by Bill Wagner in a post entitled "A C# 6 gotcha: Initialization vs. Expression Bodied Members".

While expression-bodied members are lambda expression-like, they are not lambda expressions. The fundamental difference is that a lambda expression results in either a delegate instance or an expression tree. Expression-bodied members are just a directive to the compiler to generate a property behind the scenes. The similarity (more or less) starts and end with the arrow (=>).

I'll also add that expression-bodied members are not limited to property members. They work on all these members:

  • Properties
  • Indexers
  • Methods
  • Operators

Added in C# 7.0

However, they do not work on these members:

  • Nested Types
  • Events
  • Fields

The term 'ng' is not recognized as the name of a cmdlet

This powershell script worked to add the correct setting to my Environment Variable "Path" ( As a per-user setting. ) It adds: %AppData%\npm ...and then restart the command line that uses "ng"

   $existingPath = [System.Environment]::GetEnvironmentVariable("Path","User")      
   write-host "existing PATH variable is $existingPath"                                          
   $newPath = "%AppData%\npm;$existingPath"                                          
   write-host "new      PATH will be     $newPath"                                               

   # update here                                                                                      
   [System.Environment]::SetEnvironmentVariable("Path", $newPath, "User")           

   $finalPath = [System.Environment]::GetEnvironmentVariable("Path","User")         
   write-host "final    PATH variable is $finalPath"                                             

CSS Circular Cropping of Rectangle Image

If you can live without the <img> tag, I suggest you use the photo as a background image.

_x000D_
_x000D_
.cropcircle{_x000D_
    width: 250px;_x000D_
    height: 250px;_x000D_
    border-radius: 100%;_x000D_
    background: #eee no-repeat center;_x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
#image1{_x000D_
    background-image: url(http://www.voont.com/files/images/edit/7-ridiculous-ways-boost-self-esteem/happy.jpg);_x000D_
}
_x000D_
<div id="image1" class="cropcircle"></div>
_x000D_
_x000D_
_x000D_

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Edit the configuration and then in the box: Script path, select your .py file!

Java: is there a map function?

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

How to check if a string contains text from an array of substrings in JavaScript?

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}

How to capture a list of specific type with mockito

If you're not afraid of old java-style (non type safe generic) semantics, this also works and is simple'ish:

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(subject.method(argument.capture()); // run your code
List<SomeType> list = argument.getValue(); // first captured List, etc.

How do I tell Maven to use the latest version of a dependency?

Unlike others I think there are many reasons why you might always want the latest version. Particularly if you are doing continuous deployment (we sometimes have like 5 releases in a day) and don't want to do a multi-module project.

What I do is make Hudson/Jenkins do the following for every build:

mvn clean versions:use-latest-versions scm:checkin deploy -Dmessage="update versions" -DperformRelease=true

That is I use the versions plugin and scm plugin to update the dependencies and then check it in to source control. Yes I let my CI do SCM checkins (which you have to do anyway for the maven release plugin).

You'll want to setup the versions plugin to only update what you want:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>versions-maven-plugin</artifactId>
    <version>1.2</version>
    <configuration>
        <includesList>com.snaphop</includesList>
        <generateBackupPoms>false</generateBackupPoms>
        <allowSnapshots>true</allowSnapshots>
    </configuration>
</plugin>

I use the release plugin to do the release which takes care of -SNAPSHOT and validates that there is a release version of -SNAPSHOT (which is important).

If you do what I do you will get the latest version for all snapshot builds and the latest release version for release builds. Your builds will also be reproducible.

Update

I noticed some comments asking some specifics of this workflow. I will say we don't use this method anymore and the big reason why is the maven versions plugin is buggy and in general is inherently flawed.

It is flawed because to run the versions plugin to adjust versions all the existing versions need to exist for the pom to run correctly. That is the versions plugin cannot update to the latest version of anything if it can't find the version referenced in the pom. This is actually rather annoying as we often cleanup old versions for disk space reasons.

Really you need a separate tool from maven to adjust the versions (so you don't depend on the pom file to run correctly). I have written such a tool in the the lowly language that is Bash. The script will update the versions like the version plugin and check the pom back into source control. It also runs like 100x faster than the mvn versions plugin. Unfortunately it isn't written in a manner for public usage but if people are interested I could make it so and put it in a gist or github.

Going back to workflow as some comments asked about that this is what we do:

  1. We have 20 or so projects in their own repositories with their own jenkins jobs
  2. When we release the maven release plugin is used. The workflow of that is covered in the plugin's documentation. The maven release plugin sort of sucks (and I'm being kind) but it does work. One day we plan on replacing this method with something more optimal.
  3. When one of the projects gets released jenkins then runs a special job we will call the update all versions job (how jenkins knows its a release is a complicated manner in part because the maven jenkins release plugin is pretty crappy as well).
  4. The update all versions job knows about all the 20 projects. It is actually an aggregator pom to be specific with all the projects in the modules section in dependency order. Jenkins runs our magic groovy/bash foo that will pull all the projects update the versions to the latest and then checkin the poms (again done in dependency order based on the modules section).
  5. For each project if the pom has changed (because of a version change in some dependency) it is checked in and then we immediately ping jenkins to run the corresponding job for that project (this is to preserve build dependency order otherwise you are at the mercy of the SCM Poll scheduler).

At this point I'm of the opinion it is a good thing to have the release and auto version a separate tool from your general build anyway.

Now you might think maven sort of sucks because of the problems listed above but this actually would be fairly difficult with a build tool that does not have a declarative easy to parse extendable syntax (aka XML).

In fact we add custom XML attributes through namespaces to help hint bash/groovy scripts (e.g. don't update this version).

how to start stop tomcat server using CMD?

This is what I used to start and stop tomcat 7.0.29, using ant 1.8.2. Works fine for me, but leaves the control in the started server window. I have not tried it yet, but I think if I change the "/K" in the startup sequence to "/C", it may not even do that.

<target name="tomcat-stop">
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/C start cmd.exe /C shutdown.bat"/>
    </exec>
</target>



<target name="tomcat-start" depends="tomcat-stop" >
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/K start cmd.exe /C startup.bat"/>
    </exec>

</target>

finding first day of the month in python

My solution to find the first and last day of the current month:

def find_current_month_last_day(today: datetime) -> datetime:
    if today.month == 2:
        return today.replace(day=28)

    if today.month in [4, 6, 9, 11]:
        return today.replace(day=30)

    return today.replace(day=31)


def current_month_first_and_last_days() -> tuple:
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    first_date = today.replace(day=1)
    last_date = find_current_month_last_day(today)
    return first_date, last_date

Change language of Visual Studio 2017 RC

  1. Go to Tools -> Options
  2. Select International Settings in Environment and on the right side of a screen you should see a combo with the list of installed language packages. (so in my case Czech, English and same as on MS Windows )
  3. Click on Ok

You have to restart Visual Studio to see the change...

If you are polish (and got polish language settings)

  1. Narzedzia -> Opcje
  2. Ustawienia miedzynarodowe in Srodowisko

Hope this helps! Have a great time in Poland!

How do I find the number of arguments passed to a Bash script?

to add the original reference:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.

When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

see Bash Reference Manual in section 3.4.2 Special Parameters:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $# "Expands to the number of positional parameters in decimal."

String parsing in Java with delimiter tab "\t" using split

String[] columnDetail = new String[11];
columnDetail = column.split("\t", -1); // unlimited
OR
columnDetail = column.split("\t", 11); // if you are sure about limit.
 * The {@code limit} parameter controls the number of times the
 * pattern is applied and therefore affects the length of the resulting
 * array.  If the limit <i>n</i> is greater than zero then the pattern
 * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
 * length will be no greater than <i>n</i>, and the array's last entry
 * will contain all input beyond the last matched delimiter.  If <i>n</i>
 * is non-positive then the pattern will be applied as many times as
 * possible and the array can have any length.  If <i>n</i> is zero then
 * the pattern will be applied as many times as possible, the array can
 * have any length, and trailing empty strings will be discarded.

Composer Warning: openssl extension is missing. How to enable in WAMP

WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.

Usage of the backtick character (`) in JavaScript

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

To escape a backtick, put a backslash before it:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

console.log(`string text line 1
string text line 2`);

or

console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

console.log('string text line 1\n' +
'string text line 2');

or

console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \ and (a) digit(s), for example \251

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

overlay opaque div over youtube iframe

I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent as a parameter to the YouTube URL:

<iframe title=<your frame title goes here> 
    src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"  
    scrolling="no" 
    frameborder="0" 
    width="640" 
    height="390" 
    style="border:none;">
</iframe>

This allows the iframe to inherit the z-index of its container so your opaque <div> would be in front of the iframe.

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

pip install from git repo branch

This worked like charm:

pip3 install git+https://github.com/deepak1725/fabric8-analytics-worker.git@develop

Where :

develop: Branch

fabric8-analytics-worker.git : Repo

deepak1725: user

Check if an HTML input element is empty or has no value entered by user

getElementById will return false if the element was not found in the DOM.

var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
  //The element was found and the value is empty.
}

Using CSS td width absolute, position

This may not be what you want to hear, but display: table-cell does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block element inside of the table cell itself whose width you specify, e.g

<td><div style="width: 300px;">wide</div></td>

This shouldn't make much of a difference if the <table> itself is position: fixed or absolute because the position of the cells are all static relative to the table.

http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/

EDIT: I can't take credit, but as the comments say you can just use min-width instead of width on the table cell instead.

SSIS Text was truncated with status value 4

I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.

i applied the above solution and can convert my data to SQL.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I had the same problem. I uninstalled the 6.8.14 and installed back older version 5.6.8, and it worked.

Proper way to get page content

The wp_trim_words function can limit the characters too by changing the $num_words variable. For anyone who might find useful.

<?php 
$id=58; 
$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 

$customExcerpt = wp_trim_words( $content, $num_words = 26, $more = '' );
echo $customExcerpt;  
?>

Full-screen iframe with a height of 100%

<iframe src="" style="top:0;left: 0;width:100%;height: 100%; position: absolute; border: none"></iframe>

How to write loop in a Makefile?

Dynamically assign variables in the loop

The promblem with the for number in 1 2 3 4 ; do \ ...-solution is, that no variables can be assigned within the loop. $(eval VAR=...) can only be used, if the content of the assignment is known at the beginning of the target execution. If the assignment depends on the loop-variable, VAR will be empty.

To circumvent this issue, one can use the target functionality to model a loop. The following example takes the n-th file from SRC / OBJ and processes them together. Using this construction you can even use $(eval ...) to process the loop variable, as demonstrated with VAR3.

makefile

SRC = f1.c f2.cpp f3.cpp
OBJ = f1.o f2.o f3.o

SRC2 = $(addsuffix _,$(SRC))
JOIN = $(join $(SRC2),$(OBJ))

PHONY: all
all : info loop

loop : $(JOIN)

$(JOIN) :
    @# LOOP - CONTENT
    @echo "TARGET: $@"
    $(eval VAR1=$(word 1,$(subst _, ,$@)))
    @echo "VAR1: "$(VAR1)
    $(eval VAR2=$(word 2,$(subst _, ,$@)))
    @echo "VAR2: "$(VAR2)
    $(eval VAR3=$(subst .o,.x,$(VAR2)))
    @echo "You can even substitute you loop variable VAR3: "$(VAR3)
    #g++ -o $(VAR2) $(VAR1)
    @echo

PHONY: info
info:
    @printf "\n"
    @echo "JOIN: "$(JOIN)
    @printf "\n"

output

$ make

JOIN: f1.c_f1.o f2.cpp_f2.o f3.cpp_f3.o

TARGET: f1.c_f1.o
VAR1: f1.c
VAR2: f1.o
You can even substitute you loop variable VAR3: f1.x
#g++ -o f1.o f1.c

TARGET: f2.cpp_f2.o
VAR1: f2.cpp
VAR2: f2.o
You can even substitute you loop variable VAR3: f2.x
#g++ -o f2.o f2.cpp

TARGET: f3.cpp_f3.o
VAR1: f3.cpp
VAR2: f3.o
You can even substitute you loop variable VAR3: f3.x
#g++ -o f3.o f3.cpp

How to add elements of a string array to a string array list?

Use asList() method. From java Doc asList

List<String> species = Arrays.asList(speciesArr);

Is it possible to find out the users who have checked out my project on GitHub?

I believe this is an old question, and the Traffic was introduced by Github in 2014. Here is the link to the description of Traffic, that tells you the views on your repositories.

jQuery event for images loaded

Waiting for all images to load...
I found the anwser to my problem with jfriend00 here jquery: how to listen to the image loaded event of one container div? .. and "if (this.complete)"
Waiting for the all thing to load and some possibly in cache !.. and i have added the "error" event... it's robust across all browsers

$(function() { // Wait dom ready
    var $img = $('img'), // images collection
        totalImg = $img.length,
        waitImgDone = function() {
            totalImg--;
            if (!totalImg) {
                console.log($img.length+" image(s) chargée(s) !");
            }
        };
    $img.each(function() {
        if (this.complete) waitImgDone(); // already here..
        else $(this).load(waitImgDone).error(waitImgDone); // completed...
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

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

In case anybody still wondering about this issue.

try this :

new android.support.v7.app.AlertDialog.Builder(this)

ImportError: cannot import name main when running pip --version command in windows7 32 bit

try this

#!/usr/bin/python
# GENERATED BY DEBIAN

import sys

# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.i
try:
    from pip import main
except ImportError:
    from pip._internal import main
if __name__ == '__main__':
    sys.exit(main())

How to pass an array into a SQL Server stored procedure

There is no support for array in sql server but there are several ways by which you can pass collection to a stored proc .

  1. By using datatable
  2. By using XML.Try converting your collection in an xml format and then pass it as an input to a stored procedure

The below link may help you

passing collection to a stored procedure

Reliable method to get machine's MAC address in C#

let's say I have a TcpConnection using my local ip of 192.168.0.182. Then if I will like to know the mac address of that NIC I will call the meothod as: GetMacAddressUsedByIp("192.168.0.182")

public static string GetMacAddressUsedByIp(string ipAddress)
    {
        var ips = new List<string>();
        string output;

        try
        {
            // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;

            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ipconfig";
            p.StartInfo.Arguments = "/all";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

        }
        catch
        {
            return null;
        }

        // pattern to get all connections
        var pattern = @"(?xis) 
(?<Header>
     (\r|\n) [^\r]+ :  \r\n\r\n
)
(?<content>
    .+? (?= ( (\r\n\r\n)|($)) )
)";

        List<Match> matches = new List<Match>();

        foreach (Match m in Regex.Matches(output, pattern))
            matches.Add(m);

        var connection = matches.Select(m => new
        {
            containsIp = m.Value.Contains(ipAddress),
            containsPhysicalAddress = Regex.Match(m.Value, @"(?ix)Physical \s Address").Success,
            content = m.Value
        }).Where(x => x.containsIp && x.containsPhysicalAddress)
        .Select(m => Regex.Match(m.content, @"(?ix)  Physical \s address [^:]+ : \s* (?<Mac>[^\s]+)").Groups["Mac"].Value).FirstOrDefault();

        return connection;
    }

preferredStatusBarStyle isn't called

The NavigationController or TabBarController are the ones that need to provide the style. Here is how I solved: https://stackoverflow.com/a/39072526/242769

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

According to documentation mod_ssl:

SSLCertificateFile: 
   Name: SSLCertificateFile
   Description: Server PEM-encoded X.509 certificate file

Certificate file should be PEM-encoded X.509 Certificate file:

openssl x509 -inform DER -in certificate.cer -out certificate.pem

jQuery select2 get value of select tag?

$("#first").select2('data') will return all data as map

Returning JSON object as response in Spring Boot

If you need to return a JSON object using a String, then the following should work:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...

@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping
    @RequestMapping("/")
    public ResponseEntity<JsonNode> get() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
        return ResponseEntity.ok(json);
    }
    ...
}

Add tooltip to font awesome icon

The issue of adding tooltips to any HTML-Output (not only FontAwesome) is an entire book on its own. ;-)

The default way would be to use the title-attribute:

  <div id="welcomeText" title="So nice to see you!">
    <p>Welcome Harriet</p>
  </div>

or

<i class="fa fa-cog" title="Do you like my fa-coq icon?"></i>

But since most people (including me) do not like the standard-tooltips, there are MANY tools out there which will "beautify" them and offer all sort of enhancements. My personal favourites are jBox and qtip2.

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

Letter Count on a string

You have a number of problems:

  • There's a problem with your indentation as others already pointed out.
  • There's no need to have nested loops. Just one loop is enough.
  • You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.

This code fixes all these errors:

def count_letters(word, char):
    count = 0
    for c in word:
        if char == c:
            count += 1
    return count

A much more concise way to write this is to use a generator expression:

def count_letters(word, char):
    return sum(char == c for c in word)

Or just use the built-in method count that does this for you:

print 'abcbac'.count('c')

Android - get children inside a View?

This method takes all views inside a layout, this is similar to Alexander Kulyakhtin's answer. The difference is, it accepts any type of parent layouts & returns an Array List of views.

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

Duplicate Symbols for Architecture arm64

Using Xcode 8, "Update project to recommended settings" option turned ON 'No Common Blocks' for my project.

Turning it back to OFF fixed everything up.

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

From the Tools menu, click on Options, select Designers from the side menu and untick prevent changes that can lead to recreation of a table. Then save the changes

Copy Data from a table in one Database to another separate database

Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON to the top, else you will get an error. This is for SQL Server

SET IDENTITY_INSERT MOB.MobileApplication1 ON
INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
      (m.MobileApplicationDetailId,
       m.MobilePlatformId)
SELECT ma.MobileApplicationId,
       ma.MobilePlatformId 
FROM [SERVER2].DB.MOB.MobileApplication2 ma

Numpy Resize/Rescale Image

If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:

#simple image scaling to (nR x nC) size
def scale(im, nR, nC):
  nR0 = len(im)     # source number of rows 
  nC0 = len(im[0])  # source number of columns 
  return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]  
             for c in range(nC)] for r in range(nR)]

Example usage: resizing a (30 x 30) image to (100 x 200):

import matplotlib.pyplot as plt

def sqr(x):
  return x*x

def f(r, c, nR, nC):
  return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0

# a red circle on a canvas of size (nR x nC)
def circ(nR, nC):
  return [[ [f(r, c, nR, nC), 0, 0] 
             for c in range(nC)] for r in range(nR)]

plt.imshow(scale(circ(30, 30), 100, 200))

Output: scaled image

This works to shrink/scale images, and works fine with numpy arrays.

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

Fast way of finding lines in one file that are not in another?

The comm command (short for "common") may be useful comm - compare two sorted files line by line

#find lines only in file1
comm -23 file1 file2 

#find lines only in file2
comm -13 file1 file2 

#find lines common to both files
comm -12 file1 file2 

The man file is actually quite readable for this.

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

Getting the length of two-dimensional array

Assuming that the length is same for each array in the second dimension, you can use

public class B {    
 public static void main(String [] main){
    int [] [] nir= new int [2] [3];
    System.out.println(nir[0].length);
 }
}

Navigation bar show/hide

This isn't something that can fit into a few lines of code, but this is one approach that might work for you.

To hide the navigation bar:

[[self navigationController] setNavigationBarHidden:YES animated:YES];

To show it:

[[self navigationController] setNavigationBarHidden:NO animated:YES];

Documentation for this method is available here.

To listen for a "double click" or double-tap, subclass UIView and make an instance of that subclass your view controller's view property.

In the view subclass, override its -touchesEnded:withEvent: method and count how many touches you get in a duration of time, by measuring the time between two consecutive taps, perhaps with CACurrentMediaTime(). Or test the result from [touch tapCount].

If you get two taps, your subclassed view issues an NSNotification that your view controller has registered to listen for.

When your view controller hears the notification, it fires a selector that either hides or shows the navigation bar using the aforementioned code, depending on the navigation bar's current visible state, accessed through reading the navigation bar's isHidden property.

EDIT

The part of my answer for handling tap events is probably useful back before iOS 3.1. The UIGestureRecognizer class is probably a better approach for handling double-taps, these days.

EDIT 2

The Swift way to hide the navigation bar is:

navigationController?.setNavigationBarHidden(true, animated: true)

To show it:

navigationController?.setNavigationBarHidden(false, animated: true)

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
    schoolName  = school
    cityName = city
    standardName = standard
    studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

Exporting functions from a DLL with dllexport

I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.

For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

The bigger question is why do you want to do that? What's wrong with the mangled names?

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

How to make a window always stay on top in .Net?

Based on clamum's answer, and Kevin Vuilleumier's comment about the other flag responsible for the behavior, I made this toggle that switches between on-top and not on-top with a button press.

private void button1_Click(object sender, EventArgs e)
    {
        if (on)
        {
            button1.Text = "yes on top";
            IntPtr HwndTopmost = new IntPtr(-1);
            SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
            on = false;
        }
        else
        {
            button1.Text = "not on top";
            IntPtr HwndTopmost = new IntPtr(-2);
            SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
            on = true;
        }
    }

What is the difference between `throw new Error` and `throw someObject`?

React behavior

Apart from the rest of the answers, I would like to show one difference in React.

If I throw a new Error() and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.

Example

Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).

throw new Error("The application could not authenticate.");

Error screen in react

Whereas the following code only logs into the console:

throw "The application could not authenticate.";

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Simple Pivot Table to Count Unique Values

I found an easier way of doing this. Referring to Siddarth Rout's example, if I want to count unique values in column A:

  • add a new column C and fill C2 with formula "=1/COUNTIF($A:$A,A2)"
  • drag formula down to the rest of the column
  • pivot with column A as row label, and Sum{column C) in values to get the number of unique values in column A

How to get the url parameters using AngularJS

I found solution how to use $location.search() to get parameter from URL

first in URL u need put syntax " # " before parameter like this example

"http://www.example.com/page#?key=value"

and then in your controller u put $location in function and use $location.search() to get URL parameter for

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);

Substring with reverse index

alert("xxxxxxxxxxx_456".substr(-3))

caveat: according to mdc, not IE compatible

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This question is a few years old, and there are some good suggestions for workarounds, but I didn't really notice any answers that address the core of the original question head-on. So:

  • Providing a "universal" method for viewing source in a feature phone browser (or even arbitrary third-party smartphone browser) is impossible because "view source" — via any method — is a feature implemented in the browser. So how it's accessed, or even if it can be accessed, is up to the developers of the browser. I'm sure there are plenty of browsers that intentionally prevent the user from viewing page source, and if so then you're out of luck, except maybe for workarounds like the ones offered here.

  • Workarounds such as "view source" apps external to the browser, while useful in some cases, are at best an imperfect partial solution to the original request. It's never certain that any such app will display the source of the page in the same form as it's loaded by the phone's browser.

    Modern web content changes itself in all manner of ways through browser detection, session management, etc. so that the source loaded by any external app can never be relied on to represent the source as loaded by a different app. If you're going to use an external app to load a page because you want to see the source, you might as well just use Chrome (or, on an iOS device, Safari) instead.

How to disable horizontal scrolling of UIScrollView?

Introduced in iOS 11 is a new property on UIScrollView

var contentLayoutGuide: UILayoutGuide

The documentation states that you:

Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.

Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)

example:

NSLayoutConstraint.activate([
  scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
])

Documentation: https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

What's the difference between SCSS and Sass?

Sass (Syntactically Awesome StyleSheets) have two syntaxes:

  • a newer: SCSS (Sassy CSS)
  • and an older, original: indent syntax, which is the original Sass and is also called Sass.

So they are both part of Sass preprocessor with two different possible syntaxes.

The most important difference between SCSS and original Sass:

SCSS:

  • Syntax is similar to CSS (so much that every regular valid CSS3 is also valid SCSS, but the relationship in the other direction obviously does not happen)

  • Uses braces {}

  • Uses semi-colons ;
  • Assignment sign is :
  • To create a mixin it uses the @mixin directive
  • To use mixin it precedes it with the @include directive
  • Files have the .scss extension.

Original Sass:

  • Syntax is similar to Ruby
  • No braces
  • No strict indentation
  • No semi-colons
  • Assignment sign is = instead of :
  • To create a mixin it uses the = sign
  • To use mixin it precedes it with the + sign
  • Files have the .sass extension.

Some prefer Sass, the original syntax - while others prefer SCSS. Either way, but it is worth noting that Sass’s indented syntax has not been and will never be deprecated.

Conversions with sass-convert:

# Convert Sass to SCSS
$ sass-convert style.sass style.scss

# Convert SCSS to Sass
$ sass-convert style.scss style.sass

The Sass and SCSS documentation

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

What's the easiest way to call a function every 5 seconds in jQuery?

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>

PHP Warning: Unknown: failed to open stream

Just quote for above answer of user1992554 This one worked perfectly for me in Linux Mint, to get rid of Warning: failed to open stream: Permission denied

cd /var/www
sudo chown www-data:www-data * -R
sudo usermod -a -G www-data username