Programs & Examples On #Savestate

How to use onSavedInstanceState example please

Store information:

static final String PLAYER_SCORE = "playerScore";
static final String PLAYER_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(PLAYER_SCORE, mCurrentScore);
    savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);

// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

If you don't want to restore information in your onCreate-Method:

Here are the examples: Recreating an Activity

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);

// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(PLAYER_SCORE);
mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}

How to stop a PowerShell script on the first error?

Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1:

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
function ThrowOnNativeFailure {
    if (-not $?)
    {
        throw 'Native Failure'
    }
}

Then in any powershell file, after the CmdletBinding and Param for the file (if present), I have the following:

$ErrorActionPreference = "Stop"
. "$PSScriptRoot\ps_support.ps1"

The duplicated ErrorActionPreference = "Stop" line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1 wrong, that needs to not silently fail!

I keep ps_support.ps1 in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1 file is.

Any native call gets this treatment:

native_call.exe
ThrowOnNativeFailure

Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)

How to use the onClick event for Hyperlink using C# code?

Wow, you have a huge misunderstanding how asp.net works.

This line of code

System.Diagnostics.Process.Start("help/AdminTutorial.html");

Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.

A very easy solution would be to change the href attribute of the link in you page_load method.

Your aspx code:

<a href="#" runat="server" id="myLink">Tutorial</a>

Your codebehind / cs code of page_load:

...
if (userinfo.user == "Admin")
{
  myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else 
{
  myLink.Attributes["href"] = "help/otherSite.html";
}
...

Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

Setting the Vim background colors

Using set bg=dark with a white background can produce nearly unreadable text in some syntax highlighting schemes. Instead, you can change the overall colorscheme to something that looks good in your terminal. The colorscheme file should set the background attribute for you appropriately. Also, for more information see:

:h color

iOS 7 - Failing to instantiate default view controller

1st option

if you want to set your custom storyboard instead of a default view controller.

Change this attribute from info.plist file

<key>UISceneStoryboardFile</key> <string>Onboarding</string>

Onboarding would be your storyboard name

to open this right-click on info.plist file and open as a source code

2nd option

1- Click on your project

2- Select your project from the target section

3- Move to Deployment interface section

4- Change your storyboard section from Main Interface field

Please remember set your storyboard initial view controller

Insert variable values in the middle of a string

Use String.Format

Pre C# 6.0

string data = "FlightA, B,C,D";
var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);

C# 6.0 -- String Interpolation

string data = "FlightA, B,C,D";
var str = $"Hi We have these flights for you: {data}. Which one do you want?";

http://www.informit.com/articles/article.aspx?p=2422807

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

A useful shortcut from inside Sublime Text:

cmd-shift-P --> Browse Packages Now open user folder.

Open new popup window without address bars in firefox & IE

Firefox 3.0 and higher have disabled setting location by default. resizable and status are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:

  • dom.disable_window_open_feature.location
  • dom.disable_window_open_feature.resizable
  • dom.disable_window_open_feature.status

You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.

One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:

window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

Send Outlook Email Via Python?

I wanted to send email using SMTPLIB, its easier and it does not require local setup. After other answers were not directly helpful, This is what i did.

Open Outlook in a browser; Go to the top right corner, click the gear icon for Settings, Choose 'Options' from the appearing drop-down list. Go to 'Accounts', click 'Pop and Imap', You will see the option: "Let devices and apps use pop",

Choose Yes option and Save changes.

Here is the code there after; Edit where neccesary. Most Important thing is to enable POP and the server code herein;

import smtplib

body = 'Subject: Subject Here .\nDear ContactName, \n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Innitials'
try:
    smtpObj = smtplib.SMTP('smtp-mail.outlook.com', 587)
except Exception as e:
    print(e)
    smtpObj = smtplib.SMTP_SSL('smtp-mail.outlook.com', 465)
#type(smtpObj) 
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('[email protected]', "password") 
smtpObj.sendmail('[email protected]', '[email protected]', body) # Or recipient@outlook

smtpObj.quit()
pass

How to clear a textbox once a button is clicked in WPF?

For example:

XAML:

<Button Content="ok" Click="Button_Click"/>
<TextBlock Name="textBoxName"/>

In code:

 private void Button_Click(object sender, RoutedEventArgs e)
{
textBoxName.Text = "";
}

How do I set the value property in AngularJS' ng-options?

You can use ng-options to achieve select tag binding to value and display members

While using this data source

countries : [
              {
                 "key": 1,
                 "name": "UAE"
             },
              {
                  "key": 2,
                  "name": "India"
              },
              {
                  "key": 3,
                  "name": "OMAN"
              }
         ]

you can use the below to bind your select tag to value and name

<select name="text" ng-model="name" ng-options="c.key as c.name for c in countries"></select>

it works great

Safely override C++ virtual functions

I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.

handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.

EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.

What SOAP client libraries exist for Python, and where is the documentation for them?

I believe soaplib has deprecated its SOAP client ('sender') in favor of suds. At this point soaplib is focused on being a web framework agnostic SOAP server ('receiver'). Currently soaplib is under active development and is usually discussed in the Python SOAP mailing list:

http://mail.python.org/mailman/listinfo/soap

How to force a web browser NOT to cache images

I made a PHP script that automatically adds the timestamps for all images in the HTML page. You just need to include this script in your pages. Enjoy!

http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/

Regex: match everything but specific pattern

Regex: match everything but:

Demo note: the newline \n is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.

Anchor note: In many languages, use \A to define the unambiguous start of string, and \z (in Python, it is \Z, in JavaScript, $ is OK) to define the very end of the string.

Dot note: In many flavors (but not POSIX, TRE, TCL), . matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s in PCRE/Boost/.NET/Python/Java and /m in Ruby) for the . to match any char including a newline.

Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\. will be declared as "world\\.", or use a character class: "world[.]"). Use raw string literals (Python r'\bworld\b'), C# verbatim string literals @"world\.", or slashy strings/regex literal notations like /world\./.

Cleaning up old remote git branches

If git branch -r shows a lot of remote-tracking branches that you're not interested in and you want to remove them only from local, use the following command:

git branch -r | grep -Ev 'HEAD|master|develop'  | xargs -r git branch -rd

A safer version would be to only remove the merged ones:

git branch -r --merged | grep -Ev 'HEAD|master|develop'  | xargs -r git branch -rd

This might be useful for large projects, where you don't need the feature branches of other teammates but there're lots of remote-tracking branches fetched upon the initial clone.

However, this step alone is not sufficient, because those deleted remote-tracking branches would come back upon next git fetch.

To stop fetching those remote-tracking branches you need to explicitly specify the refs to fetch in .git/config:

[remote "origin"]
  # fetch = +refs/heads/*:refs/remotes/origin/*    ### don't fetch everything
  fetch = +refs/heads/master:refs/remotes/origin/master
  fetch = +refs/heads/develop:refs/remotes/origin/develop
  fetch = +refs/heads/release/*:refs/remotes/origin/release/*

In the above example we only fetch master, develop and release branches, feel free to adapt as you need.

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

For loop example in MySQL

drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;

drop procedure if exists load_foo_test_data;

delimiter #
create procedure load_foo_test_data()
begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  truncate table foo;
  start transaction;
  while v_counter < v_max do
    insert into foo (val) values ( floor(0 + (rand() * 65535)) );
    set v_counter=v_counter+1;
  end while;
  commit;
end #

delimiter ;

call load_foo_test_data();

select * from foo order by id;

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

Calling a PHP function from an HTML form in the same file

You have a big misunderstanding of how the web works.

Basically, things happen this way:

  • User (well, the browser) requests test.php from your server
  • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
  • The browser displays the form, the user can interact with it.
  • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).

Instant run in Android Studio 2.0 (how to turn off)

Update August 2019

In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):enter image description here

Python and SQLite: insert into table

conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

SQL SELECT from multiple tables

select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

This is not an error message but a warning. It is very clearly explained in their website as :

This warning, i.e. not an error, message is reported when no SLF4J providers could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. Note that these providers must target slf4j-api 1.8 or later.

In the absence of a provider, SLF4J will default to a no-operation (NOP) logger provider.

https://www.slf4j.org/codes.html#StaticLoggerBinder

HTML 5: Is it <br>, <br/>, or <br />?

<br> and <br /> render differently in some browsers, so choosing either over the other isn't going to hurt your project, but do expect a bulk find..replace to affect the page render in some browsers, which may result in extra work for yourself or even embarrassment should the change affect nothing in your test browser, but break it in the preferred browser of your clients'.

I prefer <br> since it is what I have used since Erwise and Netscape Navigator (early web browsers), but there's no reason not to choose <br /> instead. It may be useful for some preprocessing, comparability, etc.

Even if your choice boils down to preferring the look of one over the other, or you (or your favourite HTML editor e.g. Dreamweaver) might like your code to be xml compliant. It's up to you.

A quick side note:

Not to be confused with br, but in addition you may also consider using wbr tags in your HTML: A word break opportunity tag, which specifies where in a text it would be ok to add a line-break.

For further reading, please have a read of the HTML5 spec.

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Your email session should be provided an authenticator instance as below

Session session = Session.getDefaultInstance(props,
    new Authenticator() {
        protected PasswordAuthentication  getPasswordAuthentication() {
        return new PasswordAuthentication(
                    "[email protected]", "password");
                }
    });

a complete example is here http://bharatonjava.wordpress.com/2012/08/27/sending-email-using-java-mail-api/

How do you change the width and height of Twitter Bootstrap's tooltips?

BS3:

.tooltip-inner { width:400px; max-width: 400px; }

How to remove button shadow (android)

A simpler way to do is adding this tag to your button:

android:stateListAnimator="@null"

though it requires API level 21 or more..

How to fit a smooth curve to my data in R?

I like loess() a lot for smoothing:

x <- 1:10
y <- c(2,4,6,8,7,12,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
lines(predict(lo), col='red', lwd=2)

Venables and Ripley's MASS book has an entire section on smoothing that also covers splines and polynomials -- but loess() is just about everybody's favourite.

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

Connect Bluestacks to Android Studio

  1. Goto Blustacks settings > Preferences > Check Enable Android Debug Bridge (ADB)
  2. Restart Bluestacks and Start Android Studio
  3. Done

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Using mysql concat() in WHERE clause?

What you have should work but can be reduced to:

select * from table where concat_ws(' ',first_name,last_name) 
like '%$search_term%';

Can you provide an example name and search term where this doesn't work?

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

How to read appSettings section in the web.config file?

You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString

Don't forget to add usingstatement at the beginning. Hope it will help.

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

READ_EXTERNAL_STORAGE permission for Android

You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use new and wonderful ask-for-permission model:

if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
    // app-defined int constant that should be quite unique

    return;
}

Sniplet found here: https://developer.android.com/training/permissions/requesting.html

Solutions 2: If it does not work try this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_PERMISSION);

return;

}

and then in callback

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Permission granted.
    } else {
        // User refused to grant permission.
    }
}
}

that is from comments. thanks

What is the difference between a framework and a library?

A framework can be made out of different libraries. Let's take an example.

Let's say you want to cook a fish curry. Then you need ingredients like oil, spices and other utilities. You also need fish which is your base to prepare your dish on (This is data of your application). all ingredients together called a framework. Now you gonna use them one by one or in combination to make your fish curry which is your final product. Compare that with a web framework which is made out of underscore.js, bootstrap.css, bootstrap.js, fontawesome, AngularJS etc. For an example, Twitter Bootstrap v.35.

Now, if you consider only one ingredient, like say oil. You can't use any oil you want because then it will ruin your fish (data). You can only use Olive Oil. Compare that with underscore.js. Now what brand of oil you want to use is up to you. Some dish was made with American Olive Oil (underscore.js) or Indian Olive Oil (lodash.js). This will only change taste of your application. Since they serve almost same purpose, their use depends on the developer's preference and they are easily replaceable.

enter image description here


Framework : A collection of libraries which provide unique properties and behavior to your application. (All ingredients)

Library : A well defined set of instructions which provide unique properties and behavior to your data. (Oil on Fish)

Plugin : A utility build for a library (ui-router -> AngularJS) or many libraries in combination (date-picker -> bootstrap.css + jQuery) without which your plugin might now work as expected.


P.S. AngularJS is a MVC framework but a JavaScript library. Because I believe Library extends default behavior of native technology (JavaScript in this case).

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

Your PHP script (external file 'email.php') should look like this:

<?php
if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]", "51 Deep comment from" .$email, $message);
}
?>

How to pass multiple parameters in a querystring

~mypage.aspx?strID=x&strName=y&strDate=z

Install windows service without InstallUtil.exe

Why not just create a setup project? It's really easy.

  1. Add a service installer to the service (you do it on the seemingly useless service "design" surface)
  2. Create a setup project and add the Service output to the setup app folder
  3. Most importantly add the Service project output to all the custom actions

Voila, and you're done.

See here for more: http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

There is also a way to prompt the user for credentials (or supply your own).

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

How can I trigger the click event of another element in ng-click using angularjs?

for jqLite just use triggerHandler with event name, To simulate a "click" try:

_x000D_
_x000D_
angular.element("tr").triggerHandler("click");
_x000D_
_x000D_
_x000D_

Here's the list of jQLite commands

How to split a comma-separated string?

A small improvement: above solutions will not remove leading or trailing spaces in the actual String. It's better to call trim before calling split. Instead of this,

 String[] animalsArray = animals.split("\\s*,\\s*");

use

 String[] animalsArray = animals.trim().split("\\s*,\\s*");

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Check your short_open_tag setting (use <?php phpinfo() ?> to see its current setting).

Splitting a continuous variable into equal sized groups

try this:

split(das, cut(das$anim, 3))

if you want to split based on the value of wt, then

library(Hmisc) # cut2
split(das, cut2(das$wt, g=3))

anyway, you can do that by combining cut, cut2 and split.

UPDATED

if you want a group index as an additional column, then

das$group <- cut(das$anim, 3)

if the column should be index like 1, 2, ..., then

das$group <- as.numeric(cut(das$anim, 3))

UPDATED AGAIN

try this:

> das$wt2 <- as.numeric(cut2(das$wt, g=3))
> das
   anim    wt wt2
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   3
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

How to open a local disk file with JavaScript?

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.

Can I pass parameters in computed properties in Vue.Js

You can use methods, but I prefer still to use computed properties instead of methods, if they're not mutating data or do not have external effects.

You can pass arguments to computed properties this way (not documented, but suggested by maintainers, don't remember where):

computed: {
   fullName: function () {
      var vm = this;
      return function (salut) {
          return salut + ' ' + vm.firstName + ' ' + vm.lastName;  
      };
   }
}

EDIT: Please do not use this solution, it only complicates code without any benefits.

Is there a REAL performance difference between INT and VARCHAR primary keys?

Allow me to say yes there is definitely a difference, taking into consideration the scope of performance (Out of the box definition):

1- Using surrogate int is faster in application because you do not need to use ToUpper(), ToLower(), ToUpperInvarient(), or ToLowerInvarient() in your code or in your query and these 4 functions have different performance benchmarks. See Microsoft performance rules on this. (performance of application)

2- Using surrogate int guarantees not changing the key over time. Even country codes may change, see Wikipedia how ISO codes changed over time. That would take lots of time to change the primary key for subtrees. (performance of data maintenance)

3- It seems there are issues with ORM solutions, such as NHibernate when PK/FK is not int. (developer performance)

Slick Carousel Uncaught TypeError: $(...).slick is not a function

Try:

function initSlider(){
    $('.references').slick({
        dots: false,
        infinite: true,
        speed: 300,
        slidesToShow: 1,
        autoplay: true,
        prevArrow: '<div class="slick-prev"><i class="fa fa-chevron-left"></i></div>',
        nextArrow: '<div class="slick-next"><i class="fa fa-chevron-right"></i></div>'
    });
}

$(document).on('ready', function () {
    initSlider();
});

Also just to be sure, make sure that you include the JS file for the slider after you include jQuery and before you include the code above to initialise.

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Well if you know the order of your words.. you can use:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'

Also you can use:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'

jQuery Determine if a matched class has a given id

I would probably use $('.mydiv').is('#foo'); That said if you know the Id why wouldnt you just apply it to the selector in the first place?

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

How to create a JavaScript callback for knowing when an image is loaded?

Image.onload() will often work.

To use it, you'll need to be sure to bind the event handler before you set the src attribute.

Related Links:

Example Usage:

_x000D_
_x000D_
    window.onload = function () {_x000D_
_x000D_
        var logo = document.getElementById('sologo');_x000D_
_x000D_
        logo.onload = function () {_x000D_
            alert ("The image has loaded!");  _x000D_
        };_x000D_
_x000D_
        setTimeout(function(){_x000D_
            logo.src = 'https://edmullen.net/test/rc.jpg';         _x000D_
        }, 5000);_x000D_
    };
_x000D_
 <html>_x000D_
    <head>_x000D_
    <title>Image onload()</title>_x000D_
    </head>_x000D_
    <body>_x000D_
_x000D_
    <img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
    <script type="text/javascript">_x000D_
_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Modify the legend of pandas bar plot

If you need to call plot multiply times, you can also use the "label" argument:

ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')

While this is not the case in the OP question, this can be helpful if the DataFrame is in long format and you use groupby before plotting.

Is there a command to refresh environment variables from the command prompt in Windows?

I liked the approach followed by chocolatey, as posted in anonymous coward's answer, since it is a pure batch approach. However, it leaves a temporary file and some temporary variables lying around. I made a cleaner version for myself.

Make a file refreshEnv.bat somewhere on your PATH. Refresh your console environment by executing refreshEnv.

@ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!

REM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w

IF [%1]==[/?] GOTO :help
IF [%1]==[/help] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[] GOTO :main

ECHO Unknown command: %1
EXIT /b 1 

:help
ECHO Refresh the environment variables in the console.
ECHO.
ECHO   refreshEnv       Refresh all environment variables.
ECHO   refreshEnv /?        Display this help.
GOTO :EOF

:main
REM Because the environment variables may refer to other variables, we need a 2-step approach.
REM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and
REM may pose problems for files with an '!' in the name.
REM The option used here is to create a temporary batch file that will define all the variables.

REM Check to make sure we don't overwrite an actual file.
IF EXIST %TEMP%\__refreshEnvironment.bat (
  ECHO Environment refresh failed!
  ECHO.
  ECHO This script uses a temporary file "%TEMP%\__refreshEnvironment.bat", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.
  EXIT /b 1
)

REM Read the system environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"`) DO (
  REM /I -> ignore casing, since PATH may also be called Path
  IF /I NOT [%%I]==[PATH] (
    ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
  )
)

REM Read the user environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment`) DO (
  REM /I -> ignore casing, since PATH may also be called Path
  IF /I NOT [%%I]==[PATH] (
    ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
  )
)

REM PATH is a special variable: it is automatically merged based on the values in the
REM system and user variables.
REM Read the PATH variable from the system and user environment variables.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) DO (
  ECHO SET PATH=%%K>>%TEMP%\__refreshEnvironment.bat
)
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment /v PATH`) DO (
  ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\__refreshEnvironment.bat
)

REM Load the variable definitions from our temporary file.
CALL %TEMP%\__refreshEnvironment.bat

REM Clean up after ourselves.
DEL /Q %TEMP%\__refreshEnvironment.bat

ECHO Environment successfully refreshed.

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

Sort matrix according to first column in R

Read the data:

foo <- read.table(text="1 349
  1 393
  1 392
  4 459
  3 49
  3 32
  2 94")

And sort:

foo[order(foo$V1),]

This relies on the fact that order keeps ties in their original order. See ?order.

How to launch multiple Internet Explorer windows/tabs from batch file?

Try this in your batch file:

@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

xs:boolean is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:

 <xs:simpleType name="my:boolean">
    <xs:restriction base="xs:string">
      <xs:enumeration value="True"/>
      <xs:enumeration value="False"/>
    </xs:restriction>
  </xs:simpleType>

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

How to find the width of a div using vanilla JavaScript?

Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

var elem = document.getElementById("myDiv");
if(elem) {
   var rect = elem.getBoundingClientRect();
   console.log(rect.width);  
}

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

How to create a list of objects?

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):
    pass

my_types = [str, int, float, MyClass]

Python conversion between coordinates

If your coordinates are stored as complex numbers you can use cmath

What's the difference between utf8_general_ci and utf8_unicode_ci?

I wanted to know what is the performance difference between using utf8_general_ci and utf8_unicode_ci, but I did not find any benchmarks listed on the internet, so I decided to create benchmarks myself.

I created a very simple table with 500,000 rows:

CREATE TABLE test(
  ID INT(11) DEFAULT NULL,
  Description VARCHAR(20) DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;

Then I filled it with random data by running this stored procedure:

CREATE PROCEDURE randomizer()
BEGIN
  DECLARE i INT DEFAULT 0;
  DECLARE random CHAR(20) ;
  theloop: loop
    SET random = CONV(FLOOR(RAND() * 99999999999999), 20, 36);
    INSERT INTO test VALUES (i+1, random);
    SET i=i+1;
    IF i = 500000 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END

Then I created the following stored procedures to benchmark simple SELECT, SELECT with LIKE, and sorting (SELECT with ORDER BY):

CREATE PROCEDURE benchmark_simple_select()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description = 'test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_select_like()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description LIKE '%test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_order_by()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE ID > FLOOR(1 + RAND() * (400000 - 1))
    ORDER BY Description COLLATE utf8_general_ci LIMIT 1000;
    SET i = i + 1;
    IF i = 10 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

In the stored procedures above utf8_general_ci collation is used, but of course during the tests I used both utf8_general_ci and utf8_unicode_ci.

I called each stored procedure 5 times for each collation (5 times for utf8_general_ci and 5 times for utf8_unicode_ci) and then calculated the average values.

My results are:

benchmark_simple_select()

  • with utf8_general_ci: 9,957 ms
  • with utf8_unicode_ci: 10,271 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 3.2%.

benchmark_select_like()

  • with utf8_general_ci: 11,441 ms
  • with utf8_unicode_ci: 12,811 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 12%.

benchmark_order_by()

  • with utf8_general_ci: 11,944 ms
  • with utf8_unicode_ci: 12,887 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 7.9%.

PHP: merge two arrays while keeping keys instead of reindexing?

Try array_replace_recursive or array_replace functions

$a = array('userID' => 1, 'username'=> 2);
array (
  userID => 1,
  username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
  'userID' => 1,
  'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
  userID => 1,
  username => 2,
  companyID => 3
)

http://php.net/manual/en/function.array-replace-recursive.php

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

Google Gson - deserialize list<class> object? (generic type)

public static final <T> List<T> getList(final Class<T[]> clazz, final String json)
{
    final T[] jsonToObject = new Gson().fromJson(json, clazz);

    return Arrays.asList(jsonToObject);
}

Example:

getList(MyClass[].class, "[{...}]");

Asyncio.gather vs asyncio.wait

Although similar in general cases ("run and get results for many tasks"), each function has some specific functionality for other cases:

asyncio.gather()

Returns a Future instance, allowing high level grouping of tasks:

import asyncio
from pprint import pprint

import random


async def coro(tag):
    print(">", tag)
    await asyncio.sleep(random.uniform(1, 3))
    print("<", tag)
    return tag


loop = asyncio.get_event_loop()

group1 = asyncio.gather(*[coro("group 1.{}".format(i)) for i in range(1, 6)])
group2 = asyncio.gather(*[coro("group 2.{}".format(i)) for i in range(1, 4)])
group3 = asyncio.gather(*[coro("group 3.{}".format(i)) for i in range(1, 10)])

all_groups = asyncio.gather(group1, group2, group3)

results = loop.run_until_complete(all_groups)

loop.close()

pprint(results)

All tasks in a group can be cancelled by calling group2.cancel() or even all_groups.cancel(). See also .gather(..., return_exceptions=True),

asyncio.wait()

Supports waiting to be stopped after the first task is done, or after a specified timeout, allowing lower level precision of operations:

import asyncio
import random


async def coro(tag):
    print(">", tag)
    await asyncio.sleep(random.uniform(0.5, 5))
    print("<", tag)
    return tag


loop = asyncio.get_event_loop()

tasks = [coro(i) for i in range(1, 11)]

print("Get first result:")
finished, unfinished = loop.run_until_complete(
    asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED))

for task in finished:
    print(task.result())
print("unfinished:", len(unfinished))

print("Get more results in 2 seconds:")
finished2, unfinished2 = loop.run_until_complete(
    asyncio.wait(unfinished, timeout=2))

for task in finished2:
    print(task.result())
print("unfinished2:", len(unfinished2))

print("Get all other results:")
finished3, unfinished3 = loop.run_until_complete(asyncio.wait(unfinished2))

for task in finished3:
    print(task.result())

loop.close()

How to integrate SAP Crystal Reports in Visual Studio 2017

Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

Do something if screen width is less than 960 px

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Below config worked for me. Refer this link for more details.

<dependency>
 <groupId>com.oracle.jdbc</groupId>
 <artifactId>ojdbc7</artifactId>
 <version>12.1.0.2</version>
</dependency>

Spring Boot without the web server

If you need web functionality in your application (like org.springframework.web.client.RestTemplate for REST calls) but you don't want to start a TOMCAT server, just exclude it in the POM:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

get dataframe row count based on conditions

For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

In [1]: import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))


In [2]: df.head()
Out[2]:
          A         B         C         D
0 -2.019868  1.227246 -0.489257  0.149053
1  0.223285 -0.087784 -0.053048 -0.108584
2 -0.140556 -0.299735 -1.765956  0.517803
3 -0.589489  0.400487  0.107856  0.194890
4  1.309088 -0.596996 -0.623519  0.020400

In [3]: %time sum((df['A']>0) & (df['B']>0))
CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
Wall time: 1.12 ms
Out[3]: 4

In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
Wall time: 1.42 ms
Out[4]: 4

Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

Returning an array using C

You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:

char* returnArrayPointer() 
{
static char array[SIZE];

// do something in your array here

return array; 
}

You can than use it without worrying about memory management.

int main() 
{
char* myArray = returnArrayPointer();
/* use your array here */
/* don't worry to free memory here */
}

In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!

How to print (using cout) a number in binary form?

Similar to what is already posted, just using bit-shift and mask to get the bit; usable for any type, being a template (only not sure if there is a standard way to get number of bits in 1 byte, I used 8 here).

#include<iostream>
#include <climits>

template<typename T>
void printBin(const T& t){
    size_t nBytes=sizeof(T);
    char* rawPtr((char*)(&t));
    for(size_t byte=0; byte<nBytes; byte++){
        for(size_t bit=0; bit<CHAR_BIT; bit++){
            std::cout<<(((rawPtr[byte])>>bit)&1);
        }
    }
    std::cout<<std::endl;
};

int main(void){
    for(int i=0; i<50; i++){
        std::cout<<i<<": ";
        printBin(i);
    }
}

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

SELECT query with CASE condition and SUM()

Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

What is null in Java?

An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Visual Studio Code: format is not using indent settings

Also make sure your Workspace Settings aren't overriding your User Settings. The UI doesn't make it very obvious which settings you're editing and "File > Preferences > Settings" defaults to User Settings even though Workspace Settings trump User Settings.

enter image description here

You can also edit Workspace settings directly: /.vscode/settings.json

How to create EditText accepts Alphabets only in android?

EditText state = (EditText) findViewById(R.id.txtState);


                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(state.getText().toString());
                boolean bs = ms.matches();
                if (bs == false) {
                    if (ErrorMessage.contains("invalid"))
                        ErrorMessage = ErrorMessage + "state,";
                    else
                        ErrorMessage = ErrorMessage + "invalid state,";

                }

Android Failed to install HelloWorld.apk on device (null) Error

I ran into the same problem and tried increasing the ADB connection timeout... Didn't work.

I tried putting the "android-sdk/tools" and "android-sdk/platform-tools" in the PATH variable.... No effect.

I tried restarting Eclipse and letting the AVD startup before running. Same problem.

I can sometimes get it to work with a combination of closing and reopening the project, followed by cleaning and rebuilding the project. It doesn't always work, but since I didn't restart the AVD this last time, I think the problem lies within Eclipse itself. You might try deleting everything in the "bin" directory of your project and then cleaning and rebuilding. It might be some temporary or intermediate files not getting deleted properly. Another thing I had to do was delete my AVD. It didn't delete properly, and I had to go in and manually delete the AVD's subfolder and then re-create the AVD. Some combination of these clears the problem up temporarily. Hope that helps.

Python pandas: how to specify data types when reading an Excel file?

The read_excel() function has a converters argument, where you can apply functions to input in certain columns. You can use this to keep them as strings. Documentation:

Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.

Example code:

pandas.read_excel(my_file, converters = {my_str_column: str})

C linked list inserting node at the end

I would like to mention the key before writing the code for your consideration.

//Key

temp= address of new node allocated by malloc function (member od alloc.h library in C )

prev= address of last node of existing link list.

next = contains address of next node

struct node {
    int data;
    struct node *next;
} *head;

void addnode_end(int a) {
    struct node *temp, *prev;
    temp = (struct node*) malloc(sizeof(node));
    if (temp == NULL) {
        cout << "Not enough memory";
    } else {
        node->data = a;
        node->next = NULL;
        prev = head;

        while (prev->next != NULL) {
            prev = prev->next;
        }

        prev->next = temp;
    }
}

How to get on scroll events?

You could use a @HostListener decorator. Works with Angular 4 and up.

import { HostListener } from '@angular/core';

@HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset = window.pageYOffset 
          || document.documentElement.scrollTop 
          || document.body.scrollTop || 0;
}

How to Select Top 100 rows in Oracle?

First 10 customers inserted into db (table customers):

select * from customers where customer_id <=
(select  min(customer_id)+10 from customers)

Last 10 customers inserted into db (table customers):

select * from customers where customer_id >=
(select  max(customer_id)-10 from customers)

Hope this helps....

How to get video duration, dimension and size in PHP?

If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):

wp_get_attachment_metadata($videoID);

helped me a lot. thats why i'm posting it, although its just for wordpress users.

Generate .pem file used to set up Apple Push Notifications

Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.

please see below screnshot

pandas groupby sort within groups

You could also just do it in one go, by doing the sort first and using head to take the first 3 of each group.

In[34]: df.sort_values(['job','count'],ascending=False).groupby('job').head(3)

Out[35]: 
   count     job source
4      7   sales      E
2      6   sales      C
1      4   sales      B
5      5  market      A
8      4  market      D
6      3  market      B

How do I skip an iteration of a `foreach` loop?

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

List<String> to ArrayList<String> conversion issue

In Kotlin List can be converted into ArrayList through passing it as a constructor parameter.

ArrayList(list)

A simple algorithm for polygon intersection

Here's a simple-and-stupid approach: on input, discretize your polygons into a bitmap. To intersect, AND the bitmaps together. To produce output polygons, trace out the jaggy borders of the bitmap and smooth the jaggies using a polygon-approximation algorithm. (I don't remember if that link gives the most suitable algorithms, it's just the first Google hit. You might check out one of the tools out there to convert bitmap images to vector representations. Maybe you could call on them without reimplementing the algorithm?)

The most complex part would be tracing out the borders, I think.

Back in the early 90s I faced something like this problem at work, by the way. I muffed it: I came up with a (completely different) algorithm that would work on real-number coordinates, but seemed to run into a completely unfixable plethora of degenerate cases in the face of the realities of floating-point (and noisy input). Perhaps with the help of the internet I'd have done better!

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

Get text from DataGridView selected cells

Try this:

Dim i = Datagridview1.currentrow.index
textbox1.text = datagridview1.item(columnindex, i).value

It should work :)

How to set the component size with GridLayout? Is there a better way?

An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

In Windows 10, Windows Defender has a feature of core isolation which uses virtualisation technology that will also interupt in working of HAXM. Disable it and try again. In my case disabling it solved my issue.

How to install latest version of openssl Mac OS X El Capitan

I reached this page when I searched for information about openssl being keg-only. I believe I have understood the reason why Homebrew is taking this action now. My solution may work for you:

  • Use the following command to make the new openssl command available (assuming you have adjusted PATH to put /usr/local/bin before /usr/bin): ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/

  • When compiling with openssl, follow Homebrew's advice and use -I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib

  • Alternatively, you can make these settings permanent by putting the following lines in your .bash_profile or .bashrc: export CPATH=/usr/local/opt/openssl/include export LIBRARY_PATH=/usr/local/opt/openssl/lib

how to calculate percentage in python

Percent calculation that worked for me:

(new_num - old_num) / old_num * 100.0

Generate MD5 hash string with T-SQL

Solution:

SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)

How to use SharedPreferences in Android to store, fetch and edit values

To store values in shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

To retrieve values from shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

rand() between 0 and 1

rand() / double(RAND_MAX) generates a floating-point random number between 0 (inclusive) and 1 (inclusive), but it's not a good way for the following reasons (because RAND_MAX is usually 32767):

  1. The number of different random numbers that can be generated is too small: 32768. If you need more different random numbers, you need a different way (a code example is given below)
  2. The generated numbers are too coarse-grained: you can get 1/32768, 2/32768, 3/32768, but never anything in between.
  3. Limited states of random number generator engine: after generating RAND_MAX random numbers, implementations usually start to repeat the same sequence of random numbers.

Due to the above limitations of rand(), a better choice for generation of random numbers between 0 (inclusive) and 1 (exclusive) would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    std::mt19937_64 rng;
    // initialize the random number generator with time-dependent seed
    uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
    rng.seed(ss);
    // initialize a uniform distribution between 0 and 1
    std::uniform_real_distribution<double> unif(0, 1);
    // ready to generate random numbers
    const int nSimulations = 10;
    for (int i = 0; i < nSimulations; i++)
    {
        double currentRandomNumber = unif(rng);
        std::cout << currentRandomNumber << std::endl;
    }
    return 0;
}

This is easy to modify to generate random numbers between 1 (inclusive) and 2 (exclusive) by replacing unif(0, 1) with unif(1, 2).

Multidimensional Lists in C#

Why don't you use a List<People> instead of a List<List<string>> ?

How to check if another instance of the application is running

It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

How to recursively delete an entire directory with PowerShell 2.0?

For some reason John Rees' answer sometimes did not work in my case. But it led me in the following direction. First I try to delete the directory recursively with the buggy -recurse option. Afterwards I descend into every subdir that's left and delete all files.

function Remove-Tree($Path)
{ 
    Remove-Item $Path -force -Recurse -ErrorAction silentlycontinue

    if (Test-Path "$Path\" -ErrorAction silentlycontinue)
    {
        $folders = Get-ChildItem -Path $Path –Directory -Force
        ForEach ($folder in $folders)
        {
            Remove-Tree $folder.FullName
        }

        $files = Get-ChildItem -Path $Path -File -Force

        ForEach ($file in $files)
        {
            Remove-Item $file.FullName -force
        }

        if (Test-Path "$Path\" -ErrorAction silentlycontinue)
        {
            Remove-Item $Path -force
        }
    }
}

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I have the same problem

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I applied the answer by neo but it did not work until I change the provider to “Provider=Microsoft.ACE.OLEDB.12.0;” in connection string.

Hope this will help if some one face the same issue.

How to change indentation in Visual Studio Code?

The Problem of auto deintending is caused due to a checkbox being active in the settings of VSCode. Follow these steps:

  1. goto preferences

  2. goto settings

  3. search 'editor:trim auto whitespace' EDITOR Picture

  4. Uncheck The box

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

Comments in Markdown

I use standard HTML tags, like

<!---
your comment goes here
and here
-->

Note the triple dash. The advantage is that it works with pandoc when generating TeX or HTML output. More information is available on the pandoc-discuss group.

C++ Get name of type in template

This trick was mentioned under a few other questions, but not here yet.

All major compilers support __PRETTY_FUNC__ (GCC & Clang) /__FUNCSIG__ (MSVC) as an extension.

When used in a template like this:

template <typename T> const char *foo()
{
    #ifdef _MSC_VER
    return __FUNCSIG__;
    #else
    return __PRETTY_FUNCTION__;
    #endif
}

It produces strings in a compiler-dependent format, that contain, among other things, the name of T.

E.g. foo<float>() returns:

  • "const char* foo() [with T = float]" on GCC
  • "const char *foo() [T = float]" on Clang
  • "const char *__cdecl foo<float>(void)" on MSVC

You can easily parse the type names out of those strings. You just need to figure out how many 'junk' characters your compiler inserts before and after the type.

You can even do that completely at compile-time.


The resulting names can slightly vary between different compilers. E.g. GCC omits default template arguments, and MSVC prefixes classes with the word class.


Here's an implementation that I've been using. Everything is done at compile-time.

Example usage:

std::cout << TypeName<float>() << '\n';
std::cout << TypeName(1.2f); << '\n';

Implementation:

#include <array>
#include <cstddef>

namespace impl
{
    template <typename T>
    constexpr const auto &RawTypeName()
    {
        #ifdef _MSC_VER
        return __FUNCSIG__;
        #else
        return __PRETTY_FUNCTION__;
        #endif
    }

    struct RawTypeNameFormat
    {
        std::size_t leading_junk = 0, trailing_junk = 0;
    };

    // Returns `false` on failure.
    inline constexpr bool GetRawTypeNameFormat(RawTypeNameFormat *format)
    {
        const auto &str = RawTypeName<int>();
        for (std::size_t i = 0;; i++)
        {
            if (str[i] == 'i' && str[i+1] == 'n' && str[i+2] == 't')
            {
                if (format)
                {
                    format->leading_junk = i;
                    format->trailing_junk = sizeof(str)-i-3-1; // `3` is the length of "int", `1` is the space for the null terminator.
                }
                return true;
            }
        }
        return false;
    }

    inline static constexpr RawTypeNameFormat format =
    []{
        static_assert(GetRawTypeNameFormat(nullptr), "Unable to figure out how to generate type names on this compiler.");
        RawTypeNameFormat format;
        GetRawTypeNameFormat(&format);
        return format;
    }();
}

// Returns the type name in a `std::array<char, N>` (null-terminated).
template <typename T>
[[nodiscard]] constexpr auto CexprTypeName()
{
    constexpr std::size_t len = sizeof(impl::RawTypeName<T>()) - impl::format.leading_junk - impl::format.trailing_junk;
    std::array<char, len> name{};
    for (std::size_t i = 0; i < len-1; i++)
        name[i] = impl::RawTypeName<T>()[i + impl::format.leading_junk];
    return name;
}

template <typename T>
[[nodiscard]] const char *TypeName()
{
    static constexpr auto name = CexprTypeName<T>();
    return name.data();
}
template <typename T>
[[nodiscard]] const char *TypeName(const T &)
{
    return TypeName<T>();
}

How to stop process from .BAT file?

Here is how to kill one or more process from a .bat file.

Step 1. Open a preferred text editor and create a new file.

step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:

taskkill /im examplename.exe

To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:

taskkill /f /im somecorporateprocess.exe

To kill more than one process you rinse and repeat the first part of step 2. Example:

taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe

or

taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe

step 3. Save your file to desired location with the .bat extension.

step 4. click newly created bat file to run it.

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

JDK was not found on the computer for NetBeans 6.5

I have same problem, and solve by this way:

  1. Open CMD
  2. Go to file netbeans.exe
  3. Press Shift Key + Right Click and copy as path Copy as path
  4. Paste on CMD look like C:\Users\unnamed>"C:\Users\unnamed\Downloads\Programs\netbeans-8.2-windows.exe"
  5. Write --javahome do same point 2 on JDK folder
  6. Write on cmd look like C:\Users\unnamed>"C:\Users\unnamed\Downloads\Programs\netbeans-8.2-windows.exe" --javahome "C:\Program Files\Java\jdk-9.0.4"

  7. Enter. Enjoy it.

Going to a specific line number using Less in Unix

You can use sed for this too -

sed -n '320123'p filename 

This will print line number 320123.

If you want a range then you can do -

sed -n '320123,320150'p filename 

If you want from a particular line to the very end then -

sed -n '320123,$'p filename 

Converting between datetime, Timestamp and datetime64

If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime().

pd.date_range('20110101','20110102',freq='H').to_pydatetime()

> [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
   datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
   ....

It also supports timezones:

pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()

[ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
 datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
....

NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime() on the entire series. You will need to call .to_pydatetime() on each individual datetime64 using a list comprehension or something similar:

datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

I had this issue running within a corporate network. I added a DNS entry for google DNS at 8.8.8.8, then my own corporate DNS server below this. Worked great after that.

How do I create a unique constraint that also allows nulls?

What you're looking for is indeed part of the ANSI standards SQL:92, SQL:1999 and SQL:2003, ie a UNIQUE constraint must disallow duplicate non-NULL values but accept multiple NULL values.

In the Microsoft world of SQL Server however, a single NULL is allowed but multiple NULLs are not...

In SQL Server 2008, you can define a unique filtered index based on a predicate that excludes NULLs:

CREATE UNIQUE NONCLUSTERED INDEX idx_yourcolumn_notnull
ON YourTable(yourcolumn)
WHERE yourcolumn IS NOT NULL;

In earlier versions, you can resort to VIEWS with a NOT NULL predicate to enforce the constraint.

Appending to list in Python dictionary

Is there a more elegant way to write this code?

Use collections.defaultdict:

from collections import defaultdict

dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

Is an HTTPS query string secure?

Yes, as long as no one is looking over your shoulder at the monitor.

The requested URL /about was not found on this server

I used http://jafty.com/blog/enable-mod_rewrite-on-apache-ec2-linux-server/ to determine that after upgrading to PHP 5.6 (from 4.9.13) it also update the http (Apache) and I needed to edit the /etc/httpd/conf/httpd.conf file, I quote...

Basically, you’ll be adding All insted of None to AllowOverride, you do not want to edit the main directory configuration, you want to edit the one that looks like this:

<Directory “/var/www/html”>

Not:

<Directory />

Then restart Apache with:

sudo service httpd restart

NOTE - in my tiredness I did change a different Directory element and it made no difference, so ensure you do it for /var/www/html

The article also explains how to check mod-rewrite is enabled.

OpenSSL: unable to verify the first certificate for Experian URL

Adding additional information to emboss's answer.

To put it simply, there is an incorrect cert in your certificate chain.

For example, your certificate authority will have most likely given you 3 files.

  • your_domain_name.crt
  • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
  • TrustedRoot.crt

You most likely combined all of these files into one bundle.

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate: your_domain_name.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate: DigiCertCA.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate: TrustedRoot.crt) 
-----END CERTIFICATE-----

If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

Redownload all certs from your certificate authority and make a fresh bundle.

Does not contain a static 'main' method suitable for an entry point

For me, the error was actually produced by "Feature 'async main' is not available in C# 7.0. Please use language version 7.1 or greater". This issue was resulting in the "Does not contain a static 'main' method suitable for an entry point" message in the Error List, but the Output window showed the "not available" error. To correct this, I changed the language version from 'C# latest minor version (default)' to 'C# latest minor version (latest)' under Advanced Build Settings.

How to write a file with C in Linux?

First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE* sourceFile;
    FILE* destFile;
    char buf[50];
    int numBytes;

    if(argc!=3)
    {
        printf("Usage: fcopy source destination\n");
        return 1;
    }

    sourceFile = fopen(argv[1], "rb");
    destFile = fopen(argv[2], "wb");

    if(sourceFile==NULL)
    {
        printf("Could not open source file\n");
        return 2;
    }
    if(destFile==NULL)
    {
        printf("Could not open destination file\n");
        return 3;
    }

    while(numBytes=fread(buf, 1, 50, sourceFile))
    {
        fwrite(buf, 1, numBytes, destFile);
    }

    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

EDIT: The glibc reference has this to say:

In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).

If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

React proptype array with shape

And there it is... right under my nose:

From the react docs themselves: https://facebook.github.io/react/docs/reusable-components.html

// An array of a certain type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

Algorithm for Determining Tic Tac Toe Game Over

Another option: generate your table with code. Up to symmetry, there are only three ways to win: edge row, middle row, or diagonal. Take those three and spin them around every way possible:

def spin(g): return set([g, turn(g), turn(turn(g)), turn(turn(turn(g)))])
def turn(g): return tuple(tuple(g[y][x] for y in (0,1,2)) for x in (2,1,0))

X,s = 'X.'
XXX = X, X, X
sss = s, s, s

ways_to_win = (  spin((XXX, sss, sss))
               | spin((sss, XXX, sss))
               | spin(((X,s,s),
                       (s,X,s),
                       (s,s,X))))

These symmetries can have more uses in your game-playing code: if you get to a board you've already seen a rotated version of, you can just take the cached value or cached best move from that one (and unrotate it back). This is usually much faster than evaluating the game subtree.

(Flipping left and right can help the same way; it wasn't needed here because the set of rotations of the winning patterns is mirror-symmetric.)

Is there a numpy builtin to reject outliers from a list

Consider that all the above methods fail when your standard deviation gets very large due to huge outliers.

(Simalar as the average caluclation fails and should rather caluclate the median. Though, the average is "more prone to such an error as the stdDv".)

You could try to iteratively apply your algorithm or you filter using the interquartile range: (here "factor" relates to a n*sigma range, yet only when your data follows a Gaussian distribution)

import numpy as np

def sortoutOutliers(dataIn,factor):
    quant3, quant1 = np.percentile(dataIn, [75 ,25])
    iqr = quant3 - quant1
    iqrSigma = iqr/1.34896
    medData = np.median(dataIn)
    dataOut = [ x for x in dataIn if ( (x > medData - factor* iqrSigma) and (x < medData + factor* iqrSigma) ) ] 
    return(dataOut)

Including .cpp files

There are many reasons to discourage including a .cpp file, but it isn't strictly disallowed. Your example should compile fine.

The problem is probably that you're compiling both main.cpp and foop.cpp, which means two copies of foop.cpp are being linked together. The linker is complaining about the duplication.

Git Ignores and Maven targets

As already pointed out in comments by Abhijeet you can just add line like:

/target/**

to exclude file in \.git\info\ folder.

Then if you want to get rid of that target folder in your remote repo you will need to first manually delete this folder from your local repository, commit and then push it. Thats because git will show you content of a target folder as modified at first.

Case Insensitive String comp in C

Simple solution:

int str_case_ins_cmp(const char* a, const char* b) {
  int rc;

  while (1) {
    rc = tolower((unsigned char)*a) - tolower((unsigned char)*b);
    if (rc || !*a) {
      break;
    }

    ++a;
    ++b;
  }

  return rc;
}

How to update values in a specific row in a Python Pandas DataFrame?

Update null elements with value in the same location in other. Combines a DataFrame with other DataFrame using func to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two.

df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df1.combine_first(df2)
     A    B
0  1.0  3.0
1  0.0  4.0

more information in this link

Comparing Java enum members: == or equals()?

Here is a crude timing test to compare the two:

import java.util.Date;

public class EnumCompareSpeedTest {

    static enum TestEnum {ONE, TWO, THREE }

    public static void main(String [] args) {

        Date before = new Date();
        int c = 0;

        for(int y=0;y<5;++y) {
            for(int x=0;x<Integer.MAX_VALUE;++x) {
                if(TestEnum.ONE.equals(TestEnum.TWO)) {++c;}
                if(TestEnum.ONE == TestEnum.TWO){++c;}              
            }
        }

        System.out.println(new Date().getTime() - before.getTime());
    }   

}

Comment out the IFs one at a time. Here are the two compares from above in disassembled byte-code:

 21  getstatic EnumCompareSpeedTest$TestEnum.ONE : EnumCompareSpeedTest.TestEnum [19]
 24  getstatic EnumCompareSpeedTest$TestEnum.TWO : EnumCompareSpeedTest.TestEnum [25]
 27  invokevirtual EnumCompareSpeedTest$TestEnum.equals(java.lang.Object) : boolean [28]
 30  ifeq 36

 36  getstatic EnumCompareSpeedTest$TestEnum.ONE : EnumCompareSpeedTest.TestEnum [19]
 39  getstatic EnumCompareSpeedTest$TestEnum.TWO : EnumCompareSpeedTest.TestEnum [25]
 42  if_acmpne 48

The first (equals) performs a virtual call and tests the return boolean from the stack. The second (==) compares the object addresses directly from the stack. In the first case there is more activity.

I ran this test several times with both IFs one at a time. The "==" is ever so slightly faster.

spring data jpa @query and pageable

I tried all above solution and non worked , finally I removed the Sorting from Pagination and it worked

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

How to change Java version used by TOMCAT?

If you use the standard scripts to launch Tomcat (i.e. you haven't installed Tomcat as a windows service), you can use the setenv.bat file, to set your JRE_HOME version.

On Windows, create the file %CATALINA_BASE%\bin\setenv.bat, with content:

set "JRE_HOME=%ProgramFiles%\Java\jre1.6.0_20"

exit /b 0

And that should be it.

You can test this using %CATALINA_BASE%\bin\configtest.bat (Disclaimer: I've only checked this with a Tomcat7 installation).

Further Reading:

How to create a GUID / UUID

A simple solution to generate unique identification is to use time token and add random number to it. I prefer to prefix it with "uuid-".

Below function will generate random string of type: uuid-14d93eb1b9b4533e6. One doesn't need to generate 32 chars random string. 16 char random string is more than sufficient in this case to provide the unique UUIDs in javascript.

var createUUID = function() {
  return"uuid-"+((new Date).getTime().toString(16)+Math.floor(1E7*Math.random()).toString(16));
}

How can I use a C++ library from node.js?

You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:

http://syskall.com/how-to-write-your-own-native-nodejs-extension

How to convert Blob to File in JavaScript

Joshua P Nixon's answer is correct but I had to set last modified date also. so here is the code.

var file = new File([blob], "file_name", {lastModified: 1534584790000});

1534584790000 is an unix timestamp for "GMT: Saturday, August 18, 2018 9:33:10 AM"

How to generate XML file dynamically using PHP?

To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.

For reference you can read http://it.php.net/manual/en/book.dom.php

Now we will take a quick tour of the code below.

  • at line 2 we create an empty xml document (just specify xml version (1.0) and encoding (utf8))
  • now we need to populate the xml tree:
    • We have to create an xmlnode (line 5)
    • and we have to append this in the correct position. We are creating the root so we append this directly to the domdocument.
    • Note create element append the element to the node and return the node inserted, we save this reference to append the track nodes to the root node (incidentally called xml).

These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.

<?php    
    /* create a dom document with encoding utf8 */
    $domtree = new DOMDocument('1.0', 'UTF-8');

    /* create the root element of the xml tree */
    $xmlRoot = $domtree->createElement("xml");
    /* append it to the document created */
    $xmlRoot = $domtree->appendChild($xmlRoot);

    $currentTrack = $domtree->createElement("track");
    $currentTrack = $xmlRoot->appendChild($currentTrack);

    /* you should enclose the following two lines in a cicle */
    $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));

    $currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));

    /* get the xml printed */
    echo $domtree->saveXML();
?>

Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query

Declaring multiple variables in JavaScript

The maintainability issue can be pretty easily overcome with a little formatting, like such:

let
  my_var1 = 'foo',
  my_var2 = 'bar',
  my_var3 = 'baz'
;

I use this formatting strictly as a matter of personal preference. I skip this format for single declarations, of course, or where it simply gums up the works.

How to pass command line arguments to a shell alias?

To quote the bash man page:

There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below).

So it looks like you've answered your own question -- use a function instead of an alias

Random date in C#

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

How to get current working directory in Java?

this.getClass().getClassLoader().getResource("").getPath()

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Are you using JavaScript or jQuery besides the html? If you are, you can do something like:

HTML:

<select id='some_selector'></select>?

jQuery:

var select = '';
for (i=1;i<=100;i++){
    select += '<option val=' + i + '>' + i + '</option>';
}
$('#some_selector').html(select);

As you can see here.

Another option for compatible browsers instead of select, you can use is HTML5's input type=number:

<input type="number" min="1" max="100" value="1">

What does it mean to have an index to scalar variable error? python

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

How to align footer (div) to the bottom of the page?

This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.

<style type="text/css">
  #footer {
    position : absolute;
    bottom : 0;
    height : 40px;
    margin-top : 40px;
  }
</style>
<div id="footer">I am footer</div>

The height and margin-top should be the same so that the footer doesnt show over the content.

Cannot install signed apk to device manually, got error "App not installed"

"App not installed" shows when an app with same package already installed in same device. just delete your first application which you were using for testing purpose before making it to signed apk. This will work. cheers!

Changing permissions via chmod at runtime errors with "Operation not permitted"

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

How to test if string exists in file with Bash?

Easiest and simplest way would be:

isInFile=$(cat file.txt | grep -c "string")


if [ $isInFile -eq 0 ]; then
   #string not contained in file
else
   #string is in file at least once
fi

grep -c will return the count of how many times the string occurs in the file.

React Native android build failed. SDK location not found

Check out in your local.properties file:

sdk.dir=C\:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk

if the format is proper or not

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

Use getJSON

$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){                     
    $.each(data, function(key, value){
        console.log(key + ":" + value)
    })
});

Detail look here http://api.jquery.com/jQuery.getJSON/

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Phonegap is pretty slow: clicking a button can take up to 3 sec to display the next screen. iscroll is slow and jumpy.

There other funny bugs and issues that i was able to overcome, but in total - not fully matured.

EDIT: Per Grumpy comment, it is not Phonegap who is actually slow, it is the JS/Browser native engine

Build Eclipse Java Project from Command Line

Hi Just addition to VonC comments. I am using ecj compiler to compile my project. it was throwing expcetion that some of the classes are not found. But the project was bulding fine with javac compiler.

So just I added the classes into the classpath(which we have to pass as argument) and now its working fine... :)

Kulbir Singh

Visual Studio Code cannot detect installed git

If you have multiple environments. You could include Git Path in the VS Code Workspace Setting. For Windows, depending on your setting, you could hit Ctlr + P, search for "settings". Open setting.json(or File>Preferences>Settings). Navigate to Workspace Settings. Find "Path" and add paths to Git bin and cmd folders.

enter image description here

enter image description here

enter image description here

enter image description here

Environments can have their own paths. I discovered this when I echoed my PC %PATH% on cmd, git bin and cmd path where available but when I was working on my project, echoed %PATH% did not have git and cmd folder. Adding them, as shown above solved the issue.

Extra Notes:

On cmd, you can echo "%PATH%" and see if git bin and cmd folders are included. If not, you could concatenate using SETX PATH on, e,g

SETX PATH "%PATH%;Path_to_Git_bin;Path_to_Gt_cmd;"

This will make git available on local root but not on some environments which comes with their own paths(SETX /M PATH "%PATH%;Path_to_Git_bin;Path_to_Gt_cmd;" would have though).

In case you have a long Path that is chopped off dues to Path length(getting "Error: Truncated at X characters." message), you can increase the path length on regedit.

  • On "Search Windows", search for "regedit". Right-click to open as Admin.
  • Go to Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
  • Right-click and modify. Change value data from 0 to 1

This will increase your path length. If it is already one, then I am not sure how to proceed from there :).

[enter image description here6 [enter image description here]6

How to remove new line characters from a string?

The right choice really depends on how big the input string is and what the perforce and memory requirement are, but I would use a regular expression like

string result = Regex.Replace(s, @"\r\n?|\n|\t", String.Empty);

Or if we need to apply the same replacement multiple times, it is better to use a compiled version for the Regex like

var regex = new Regex(@"\r\n?|\n|\t", RegexOptions.Compiled); 
string result = regex.Replace(s, String.Empty);

NOTE: different scenarios requite different approaches to achieve the best performance and the minimum memory consumption

How to turn a String into a JavaScript function call?

Based on Nicolas Gauthier answer:

var strng = 'someobj.someCallback';
var data = 'someData';

var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
   //We maybe can check typeof and break the bucle if typeof != function
   func = func[funcSplit[i]];
}
func(data);

Could not find or load main class

You might have the CLASSPATH environment variable already added!!

Use following to avoid further usage of -cp . in java -cp . CLASSFILE

Add . to CLASSPATH in system properties->environment variables or by cmd

set CLASSPATH=%CLASSPATH%;.;

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Why can't I reference System.ComponentModel.DataAnnotations?

If you tried to update visual studio from vs2008 to vs2010. And your app uses framework 3.5 (and you don't want to upgrade it), and also used WCF RIA Services BETA... I have bad news... you MUST upgrade to WCF RIA Services v1 (BETA does not work on vs2010)... and due to this... you also have to install Silverlight 4 + upgrade to framework 4.0

See this: http://blog.nappisite.com/2010/05/updating-visual-studio-2008net-35-ria.html

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

Check if Nullable Guid is empty in c#

Check Nullable<T>.HasValue

if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
 //not valid GUID
}
else
{
 //Valid GUID
}

Error in <my code> : object of type 'closure' is not subsettable

In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]

Just add corresponding package name using :: e.g.

instead of tags(....)

write shiny::tags(....)

Matching a space in regex

You can also use the \b for a word boundary. For the name I would use something like this:

[^\b]+\b[^\b]+(\b|$)

EDIT Modifying this to be a regex in Perl example

if( $fullname =~ /([^\b]+)\b[^\b]+([^\b]+)(\b|$)/ ) {
 $first_name = $1;
 $last_name = $2;
}

EDIT AGAIN Based on what you want:

$new_tag = preg_replace("/[\s\t]/","",$tag);

RelativeLayout center vertical

Try aligning top and bottom of text view to one of the icon, this will make text view sharing same height as them, then set gravity to center_vertical to make the text inside text view center vertically.

<TextView 
        android:id="@+id/func_text" android:layout_toRightOf="@id/icon"
        android:layout_alignTop="@id/icon" android:layout_alignBottom="@id/icon"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:gravity="center_vertical" />

How do I base64 encode (decode) in C?

This solution is based on schulwitz answer (encoding/decoding using OpenSSL), but it is for C++ (well, original question was about C, but there are already another C++ answers here) and it uses error checking (so it's safer to use):

#include <openssl/bio.h>

std::string base64_encode(const std::string &input)
{
    BIO *p_bio_b64 = nullptr;
    BIO *p_bio_mem = nullptr;

    try
    {
        // make chain: p_bio_b64 <--> p_bio_mem
        p_bio_b64 = BIO_new(BIO_f_base64());
        if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
        BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less

        p_bio_mem = BIO_new(BIO_s_mem());
        if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
        BIO_push(p_bio_b64, p_bio_mem);

        // write input to chain
        // write sequence: input -->> p_bio_b64 -->> p_bio_mem
        if (BIO_write(p_bio_b64, input.c_str(), input.size()) <= 0)
            { throw std::runtime_error("BIO_write failed"); }

        if (BIO_flush(p_bio_b64) <= 0)
            { throw std::runtime_error("BIO_flush failed"); }

        // get result
        char *p_encoded_data = nullptr;
        auto  encoded_len    = BIO_get_mem_data(p_bio_mem, &p_encoded_data);
        if (!p_encoded_data) { throw std::runtime_error("BIO_get_mem_data failed"); }

        std::string result(p_encoded_data, encoded_len);

        // clean
        BIO_free_all(p_bio_b64);

        return result;
    }
    catch (...)
    {
        if (p_bio_b64) { BIO_free_all(p_bio_b64); }
        throw;
    }
}

std::string base64_decode(const std::string &input)
{
    BIO *p_bio_mem = nullptr;
    BIO *p_bio_b64 = nullptr;

    try
    {
        // make chain: p_bio_b64 <--> p_bio_mem
        p_bio_b64 = BIO_new(BIO_f_base64());
        if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
        BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines

        p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
        if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
        BIO_push(p_bio_b64, p_bio_mem);

        // read result from chain
        // read sequence (reverse to write): buf <<-- p_bio_b64 <<-- p_bio_mem
        std::vector<char> buf((input.size()*3/4)+1);
        std::string result;
        for (;;)
        {
            auto nread = BIO_read(p_bio_b64, buf.data(), buf.size());
            if (nread  < 0) { throw std::runtime_error("BIO_read failed"); }
            if (nread == 0) { break; } // eof

            result.append(buf.data(), nread);
        }

        // clean
        BIO_free_all(p_bio_b64);

        return result;
    }
    catch (...)
    {
        if (p_bio_b64) { BIO_free_all(p_bio_b64); }
        throw;
    }
}

Note that base64_decode returns empty string, if input is incorrect base64 sequence (openssl works in such way).

SQL: IF clause within WHERE clause

WHERE (IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber) 
             AND (IsNumber(@OrderNumber) = 1 OR OrderNumber LIKE '%' 
                                              + @OrderNumber + '%')

How to format Joda-Time DateTime to only mm/dd/yyyy?

I think this will work, if you are using JodaTime:

String strDateTime = "11/15/2013 08:00:00";
DateTime dateTime = DateTime.parse(strDateTime);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/YYYY");
String strDateOnly = fmt.print(dateTime);

I got part of this from here.

Split a vector into chunks

This splits into chunks of size ?n/k?+1 or ?n/k? and does not use the O(n log n) sort.

get_chunk_id<-function(n, k){
    r <- n %% k
    s <- n %/% k
    i<-seq_len(n)
    1 + ifelse (i <= r * (s+1), (i-1) %/% (s+1), r + ((i - r * (s+1)-1) %/% s))
}

split(1:10, get_chunk_id(10,3))

How permission can be checked at runtime without throwing SecurityException?

You can also use this:

private boolean doesUserHavePermission()
{
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}

Using ls to list directories and their total sizes

If you want more control over the size that you want to list the directories over, you can use the threshold (-t) switch as in:

$ du -ht 1000000000 | sort --reverse

du - disk usage
h - human readable format
t - threshold size

Here, we want to list all directories which are greater than 1GB in size.

$ du -ht 1G | sort --reverse

Explanation:

Units that are described in wiki follows:

K, M, G, T, P, E, Z, Y (powers of 1024) or
KB, MB, GB, TB, PB, EB, ZB, YB (powers of 1000).

C++ queue - simple example

std::queue<myclass*> that's it

spacing between form fields

I would wrap your rows in labels

<form action="doit" id="doit" method="post">
    <label>
        Name
        <input id="name" name="name" type="text" />
    </label>
    <label>
        Phone number
        <input id="phone" name="phone" type="text" />
    </label>
    <label>
        Year
        <input id="year" name="year" type="text" />
    </label>
</form>

And use

label, input {
    display: block;
}

label {
    margin-bottom: 20px;
}

Don't use brs for spacing!

Demo: http://jsfiddle.net/D8W2Q/

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.

https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]

Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

# cmd.sh
#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

How to join two sets in one line without using "|"

If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update():

S.update(T)

The return value is None, but S will be updated to be the union of the original S and T.

Pandas: ValueError: cannot convert float NaN to integer

ValueError: cannot convert float NaN to integer

From v0.24, you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs.

Given a series of whole float numbers with missing data,

s = pd.Series([1.0, 2.0, np.nan, 4.0])
s

0    1.0
1    2.0
2    NaN
3    4.0
dtype: float64

s.dtype
# dtype('float64')

You can convert it to a nullable int type (choose from one of Int16, Int32, or Int64) with,

s2 = s.astype('Int32') # note the 'I' is uppercase
s2

0      1
1      2
2    NaN
3      4
dtype: Int32

s2.dtype
# Int32Dtype()

Your column needs to have whole numbers for the cast to happen. Anything else will raise a TypeError:

s = pd.Series([1.1, 2.0, np.nan, 4.0])

s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32

Traversing text in Insert mode

For some frequently used movements and actions, I have defined the following mappings. This saves a keystroke compared to the CTRL+O combination and since I need them frequently, they pay off in the long run.

inoremap <A-$> <C-o>$
inoremap <A-^> <C-o>^
inoremap <A-h> <Left>
inoremap <A-l> <Right>
inoremap <A-O> <C-O>O
inoremap <A-o> <C-o>o

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager