Programs & Examples On #Server application

Visual Studio Code includePath

In your user settings add:

"C_Cpp.default.includePath":["path1","path2"]

How to find list of possible words from a letter matrix [Boggle Solver]

This solution also gives the direction to search in the given board

Algo:

1. Uses trie to save all the word in the english to fasten the search
2. The uses DFS to search the words in Boggle

Output:

Found "pic" directions from (4,0)(p) go  ? ?
Found "pick" directions from (4,0)(p) go  ? ? ?
Found "pickman" directions from (4,0)(p) go  ? ? ? ? ? ?
Found "picket" directions from (4,0)(p) go  ? ? ? ? ?
Found "picked" directions from (4,0)(p) go  ? ? ? ? ?
Found "pickle" directions from (4,0)(p) go  ? ? ? ? ?

Code:

from collections import defaultdict
from nltk.corpus import words
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

english_words = words.words()

# If you wan to remove stop words
# stop_words = set(stopwords.words('english'))
# english_words = [w for w in english_words if w not in stop_words]

boggle = [
    ['c', 'n', 't', 's', 's'],
    ['d', 'a', 't', 'i', 'n'],
    ['o', 'o', 'm', 'e', 'l'],
    ['s', 'i', 'k', 'n', 'd'],
    ['p', 'i', 'c', 'l', 'e']
]

# Instead of X and Y co-ordinates
# better to use Row and column
lenc = len(boggle[0])
lenr = len(boggle)

# Initialize trie datastructure
trie_node = {'valid': False, 'next': {}}

# lets get the delta to find all the nighbors
neighbors_delta = [
    (-1,-1, "?"),
    (-1, 0, "?"),
    (-1, 1, "?"),
    (0, -1, "?"),
    (0,  1, "?"),
    (1, -1, "?"),
    (1,  0, "?"),
    (1,  1, "?"),
]


def gen_trie(word, node):
    """udpates the trie datastructure using the given word"""
    if not word:
        return

    if word[0] not in node:
        node[word[0]] = {'valid': len(word) == 1, 'next': {}}

    # recursively build trie
    gen_trie(word[1:], node[word[0]])


def build_trie(words, trie):
    """Builds trie data structure from the list of words given"""
    for word in words:
        gen_trie(word, trie)
    return trie


def get_neighbors(r, c):
    """Returns the neighbors for a given co-ordinates"""
    n = []
    for neigh in neighbors_delta:
        new_r = r + neigh[0]
        new_c = c + neigh[1]

        if (new_r >= lenr) or (new_c >= lenc) or (new_r < 0) or (new_c < 0):
            continue
        n.append((new_r, new_c, neigh[2]))
    return n


def dfs(r, c, visited, trie, now_word, direction):
    """Scan the graph using DFS"""
    if (r, c) in visited:
        return

    letter = boggle[r][c]
    visited.append((r, c))

    if letter in trie:
        now_word += letter

        if trie[letter]['valid']:
            print('Found "{}" {}'.format(now_word, direction))

        neighbors = get_neighbors(r, c)
        for n in neighbors:
            dfs(n[0], n[1], visited[::], trie[letter], now_word, direction + " " + n[2])


def main(trie_node):
    """Initiate the search for words in boggle"""
    trie_node = build_trie(english_words, trie_node)

    # print the board
    print("Given board")
    for i in range(lenr):print (boggle[i])
    print ('\n')

    for r in range(lenr):
        for c in range(lenc):
            letter = boggle[r][c]
            dfs(r, c, [], trie_node, '', 'directions from ({},{})({}) go '.format(r, c, letter))


if __name__ == '__main__':
    main(trie_node)

How to Convert an int to a String?

may be you should try like this

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate+""); //gives error

Calculate distance in meters when you know longitude and latitude in java

In C++ it is done like this:

#define LOCAL_PI 3.1415926535897932385 

double ToRadians(double degrees) 
{
  double radians = degrees * LOCAL_PI / 180;
  return radians;
}

double DirectDistance(double lat1, double lng1, double lat2, double lng2) 
{
  double earthRadius = 3958.75;
  double dLat = ToRadians(lat2-lat1);
  double dLng = ToRadians(lng2-lng1);
  double a = sin(dLat/2) * sin(dLat/2) + 
             cos(ToRadians(lat1)) * cos(ToRadians(lat2)) * 
             sin(dLng/2) * sin(dLng/2);
  double c = 2 * atan2(sqrt(a), sqrt(1-a));
  double dist = earthRadius * c;
  double meterConversion = 1609.00;
  return dist * meterConversion;
}

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

Most popular screen sizes/resolutions on Android phones

Here is a list of almost all resolutions of tablets, with the most common ones in bold :

2560X1600
1366X768

1920X1200
1280X800
1280X768
1024X800
1024X768
1024X600

960X640
960X540
854X480
800X600
800X480
800X400

Happy designing .. ! :)

Android Studio cannot resolve R in imported project?

I had this same issue. The package name was wrong in two of the following three files. I manually updated the package name and everything started working again.

gen/com/example/app/BuildConfig.java

gen/com/example/app/Manifest.java

gen/com/example/app/R.java

I'm not sure what caused them to change as I've never modified these files before.

How can I compare time in SQL Server?

Just change convert datetime to time that should do the trick:

SELECT timeEvent 
FROM tbEvents 
WHERE convert(time, startHour) >= convert(time, @startHour)

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

How to check if a subclass is an instance of a class at runtime?

If there is polymorphism such as checking SQLRecoverableException vs SQLException, it can be done like that.

try {
    // sth may throw exception
    ....
} catch (Exception e) {
    if(SQLException.class.isAssignableFrom(e.getCause().getClass()))
    {
        // do sth
        System.out.println("SQLException occurs!");
    }
}

Simply say,

ChildClass child= new ChildClass();
if(ParentClass.class.isAssignableFrom(child.getClass()))
{
    // do sth
    ...
}

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

Use ASP.NET MVC validation with jquery ajax?

You can do it this way:

(Edit: Considering that you're waiting for a response json with dataType: 'json')

.NET

public JsonResult Edit(EditPostViewModel data)
{
    if(ModelState.IsValid) 
    {
       // Save  
       return Json(new { Ok = true } );
    }

    return Json(new { Ok = false } );
}

JS:

success: function (data) {
    if (data.Ok) {
      alert('success');
    }
    else {
      alert('problem');
    }
},

If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option

How to save and load cookies using Python + Selenium WebDriver

This is code I used in Windows. It works.

for item in COOKIES.split(';'):
    name,value = item.split('=', 1)
    name=name.replace(' ', '').replace('\r', '').replace('\n', '')
    value = value.replace(' ', '').replace('\r', '').replace('\n', '')
    cookie_dict={
            'name':name,
            'value':value,
            "domain": "",  # Google Chrome
            "expires": "",
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
    self.driver_.add_cookie(cookie_dict)

Insert current date/time using now() in a field using MySQL/PHP

Like Pekka said, it should work this way. I can't reproduce the problem with this self-contained example:

<?php
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo (
            id int auto_increment,
            first int,
            last int,
            whenadded DATETIME,
            primary key(id)
        )
    ');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,1,Now())');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,2,Now())');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,3,Now())');

    foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
        echo join(' | ', $row), "\n";
    }

Which (currently) prints

1 | 0 | 1 | 2012-03-23 16:00:18
2 | 0 | 2 | 2012-03-23 16:00:18
3 | 0 | 3 | 2012-03-23 16:00:18

And here's (almost) the same script using a TIMESTAMP field and DEFAULT CURRENT_TIMESTAMP:

<?php
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo (
            id int auto_increment,
            first int,
            last int,
            whenadded TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            primary key(id)
        )
    ');
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,1)');
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,2)');
    sleep(1);
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,3)');

    foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
        echo join(' | ', $row), "\n";
    }

Conveniently, the timestamp is converted to the same datetime string representation as in the first example - at least with my PHP/PDO/mysqlnd version.

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

java comparator, how to sort by integer?

public class DogAgeComparator implements Comparator<Dog> {
    public int compare(Dog o1, Dog o2) {
        return Integer.compare(o1.getAge(), o2.getId());
    }
}

Making macOS Installer Packages which are Developer ID ready

Our example project has two build targets: HelloWorld.app and Helper.app. We make a component package for each and combine them into a product archive.

A component package contains payload to be installed by the OS X Installer. Although a component package can be installed on its own, it is typically incorporated into a product archive.

Our tools: pkgbuild, productbuild, and pkgutil

After a successful "Build and Archive" open $BUILT_PRODUCTS_DIR in the Terminal.

$ cd ~/Library/Developer/Xcode/DerivedData/.../InstallationBuildProductsLocation
$ pkgbuild --analyze --root ./HelloWorld.app HelloWorldAppComponents.plist
$ pkgbuild --analyze --root ./Helper.app HelperAppComponents.plist

This give us the component-plist, you find the value description in the "Component Property List" section. pkgbuild -root generates the component packages, if you don't need to change any of the default properties you can omit the --component-plist parameter in the following command.

productbuild --synthesize results in a Distribution Definition.

$ pkgbuild --root ./HelloWorld.app \
    --component-plist HelloWorldAppComponents.plist \
    HelloWorld.pkg
$ pkgbuild --root ./Helper.app \
    --component-plist HelperAppComponents.plist \
    Helper.pkg
$ productbuild --synthesize \
    --package HelloWorld.pkg --package Helper.pkg \
    Distribution.xml 

In the Distribution.xml you can change things like title, background, welcome, readme, license, and so on. You turn your component packages and distribution definition with this command into a product archive:

$ productbuild --distribution ./Distribution.xml \
    --package-path . \
    ./Installer.pkg

I recommend to take a look at iTunes Installers Distribution.xml to see what is possible. You can extract "Install iTunes.pkg" with:

$ pkgutil --expand "Install iTunes.pkg" "Install iTunes"

Lets put it together

I usually have a folder named Package in my project which includes things like Distribution.xml, component-plists, resources and scripts.

Add a Run Script Build Phase named "Generate Package", which is set to Run script only when installing:

VERSION=$(defaults read "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Contents/Info" CFBundleVersion)

PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
TMP1_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp1.pkg"
TMP2_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp2"
TMP3_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp3.pkg"
ARCHIVE_FILENAME="${BUILT_PRODUCTS_DIR}/${PACKAGE_NAME}.pkg"

pkgbuild --root "${INSTALL_ROOT}" \
    --component-plist "./Package/HelloWorldAppComponents.plist" \
    --scripts "./Package/Scripts" \
    --identifier "com.test.pkg.HelloWorld" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/HelloWorld.pkg"
pkgbuild --root "${BUILT_PRODUCTS_DIR}/Helper.app" \
    --component-plist "./Package/HelperAppComponents.plist" \
    --identifier "com.test.pkg.Helper" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/Helper.pkg"
productbuild --distribution "./Package/Distribution.xml"  \
    --package-path "${BUILT_PRODUCTS_DIR}" \
    --resources "./Package/Resources" \
    "${TMP1_ARCHIVE}"

pkgutil --expand "${TMP1_ARCHIVE}" "${TMP2_ARCHIVE}"
    
# Patches and Workarounds

pkgutil --flatten "${TMP2_ARCHIVE}" "${TMP3_ARCHIVE}"

productsign --sign "Developer ID Installer: John Doe" \
    "${TMP3_ARCHIVE}" "${ARCHIVE_FILENAME}"

If you don't have to change the package after it's generated with productbuild you could get rid of the pkgutil --expand and pkgutil --flatten steps. Also you could use the --sign paramenter on productbuild instead of running productsign.

Sign an OS X Installer

Packages are signed with the Developer ID Installer certificate which you can download from Developer Certificate Utility.

They signing is done with the --sign "Developer ID Installer: John Doe" parameter of pkgbuild, productbuild or productsign.

Note that if you are going to create a signed product archive using productbuild, there is no reason to sign the component packages.

Developer Certificate Utility

All the way: Copy Package into Xcode Archive

To copy something into the Xcode Archive we can't use the Run Script Build Phase. For this we need to use a Scheme Action.

Edit Scheme and expand Archive. Then click post-actions and add a New Run Script Action:

In Xcode 6:

#!/bin/bash

PACKAGES="${ARCHIVE_PATH}/Packages"
  
PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
ARCHIVE_FILENAME="$PACKAGE_NAME.pkg"
PKG="${OBJROOT}/../BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

if [ -f "${PKG}" ]; then
    mkdir "${PACKAGES}"
    cp -r "${PKG}" "${PACKAGES}"
fi

In Xcode 5, use this value for PKG instead:

PKG="${OBJROOT}/ArchiveIntermediates/${TARGET_NAME}/BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

In case your version control doesn't store Xcode Scheme information I suggest to add this as shell script to your project so you can simple restore the action by dragging the script from the workspace into the post-action.

Scripting

There are two different kinds of scripting: JavaScript in Distribution Definition Files and Shell Scripts.

The best documentation about Shell Scripts I found in WhiteBox - PackageMaker How-to, but read this with caution because it refers to the old package format.

Apple Silicon

In order for the package to run as arm64, the Distribution file has to specify in its hostArchitectures section that it supports arm64 in addition to x86_64:

<options hostArchitectures="arm64,x86_64" />

Additional Reading

Known Issues and Workarounds

Destination Select Pane

The user is presented with the destination select option with only a single choice - "Install for all users of this computer". The option appears visually selected, but the user needs to click on it in order to proceed with the installation, causing some confusion.

Example showing the installer bug

Apples Documentation recommends to use <domains enable_anywhere ... /> but this triggers the new more buggy Destination Select Pane which Apple doesn't use in any of their Packages.

Using the deprecate <options rootVolumeOnly="true" /> give you the old Destination Select Pane. Example showing old Destination Select Pane


You want to install items into the current user’s home folder.

Short answer: DO NOT TRY IT!

Long answer: REALLY; DO NOT TRY IT! Read Installer Problems and Solutions. You know what I did even after reading this? I was stupid enough to try it. Telling myself I'm sure that they fixed the issues in 10.7 or 10.8.

First of all I saw from time to time the above mentioned Destination Select Pane Bug. That should have stopped me, but I ignored it. If you don't want to spend the week after you released your software answering support e-mails that they have to click once the nice blue selection DO NOT use this.

You are now thinking that your users are smart enough to figure the panel out, aren't you? Well here is another thing about home folder installation, THEY DON'T WORK!

I tested it for two weeks on around 10 different machines with different OS versions and what not, and it never failed. So I shipped it. Within an hour of the release I heart back from users who just couldn't install it. The logs hinted to permission issues you are not gonna be able to fix.

So let's repeat it one more time: We do not use the Installer for home folder installations!


RTFD for Welcome, Read-me, License and Conclusion is not accepted by productbuild.

Installer supported since the beginning RTFD files to make pretty Welcome screens with images, but productbuild doesn't accept them.

Workarounds: Use a dummy rtf file and replace it in the package by after productbuild is done.

Note: You can also have Retina images inside the RTFD file. Use multi-image tiff files for this: tiffutil -cat Welcome.tif Welcome_2x.tif -out FinalWelcome.tif. More details.


Starting an application when the installation is done with a BundlePostInstallScriptPath script:

#!/bin/bash

LOGGED_IN_USER_ID=`id -u "${USER}"`

if [ "${COMMAND_LINE_INSTALL}" = "" ]
then
    /bin/launchctl asuser "${LOGGED_IN_USER_ID}" /usr/bin/open -g PATH_OR_BUNDLE_ID
fi

exit 0

It is important to run the app as logged in user, not as the installer user. This is done with launchctl asuser uid path. Also we only run it when it is not a command line installation, done with installer tool or Apple Remote Desktop.


Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Accessing Session Using ASP.NET Web API

MVC

For an MVC project make the following changes (WebForms and Dot Net Core answer down below):

WebApiConfig.cs

public static class WebApiConfig
{
    public static string UrlPrefix         { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    ...

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}

This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:

_Layout.cshtml

<body>
    @RenderBody()

    <script type="text/javascript">
        var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';
    </script>

    @RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi')
   .done(function (data) {
       alert('session data received: ' + data.whatever);
   })
);

WebForms

Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:

public static void Register(RouteCollection routes)
{
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

And then call the following in Application_Start:

WebApiConfig.Register(RouteTable.Routes);

Dot Net Core

Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:

Startup.cs

Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    ...

    services.AddDistributedMemoryCache();
    services.AddSession();

and in the Configure function add a call to UseSession:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseSession();
    app.UseMvc();

SessionController.cs

Within your controller, add a using statement at the top:

using Microsoft.AspNetCore.Http;

and then use the HttpContext.Session object within your code like so:

    [HttpGet("set/{data}")]
    public IActionResult setsession(string data)
    {
        HttpContext.Session.SetString("keyname", data);
        return Ok("session data set");
    }

    [HttpGet("get")]
    public IActionResult getsessiondata()
    {
        var sessionData = HttpContext.Session.GetString("keyname");
        return Ok(sessionData);
    }

you should now be able to hit:

http://localhost:1234/api/session/set/thisissomedata

and then going to this URL will pull it out:

http://localhost:1234/api/session/get

Plenty more info on accessing session data within dot net core here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Performance Concerns

Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.


Security Concerns

Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.

Read Microsoft's article on Authentication and Authorization in ASP.NET Web API - https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) - https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

Change width of select tag in Twitter Bootstrap

Tested alone, <select class=input-xxlarge> sets the content width of the element to 530px. (The total width of the element is slightly smaller than that of <input class=input-xxlarge> due to different padding. If this a a problem, set the paddings in your own style sheet as desired.)

So if it does not work, the effect is prevented by some setting in your own style sheet or maybe in the use other settings for the element.

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

Since this is the first Google result for 'pandas new column from others', here's a simple example:

import pandas as pd

# make a simple dataframe
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df
#    a  b
# 0  1  3
# 1  2  4

# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0    4
# 1    6

# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
#    a  b  c
# 0  1  3  4
# 1  2  4  6

If you get the SettingWithCopyWarning you can do it this way also:

fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'

Source: https://stackoverflow.com/a/12555510/243392

And if your column name includes spaces you can use syntax like this:

df = df.assign(**{'some column name': col.values})

And here's the documentation for apply, and assign.

Merge unequal dataframes and replace missing rows with 0

Assuming df1 has all the values of x of interest, you could use a dplyr::left_join() to merge and then either a base::replace() or tidyr::replace_na() to replace the NAs as 0s:

library(tidyverse)

# dplyr only:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace(y, is.na(y), 0))

# dplyr and tidyr:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace_na(y, 0))

# In the sample data column `x` is a factor, which will give a warning with the join. This can be prevented by converting to a character before the join:
df_new <- 
  left_join(df1 %>% mutate(x = as.character(x)), 
            df2 %>% mutate(x = as.character(x)), 
            by = 'x') %>% 
    mutate(y = replace(y, is.na(y), 0))

How can I make setInterval also work when a tab is inactive in Chrome?

It is quite old question but I encountered the same issue.
If you run your web on chrome, you could read through this post Background Tabs in Chrome 57 .

Basically the interval timer could run if it haven't run out of the timer budget.
The consumption of budget is based on CPU time usage of the task inside timer.
Based on my scenario, I draw video to canvas and transport to WebRTC.
The webrtc video connection would keep updating even the tab is inactive.

However you have to use setInterval instead of requestAnimationFrame.
it is not recommended for UI rendering though.

It would be better to listen visibilityChange event and change render mechenism accordingly.

Besides, you could try @kaan-soral and it should works based on the documentation.

How To Convert A Number To an ASCII Character?

C# represents a character in UTF-16 coding rather than ASCII. Therefore converting a integer to character do not make any difference for A-Z and a-z. But I was working with ASCII Codes besides alphabets and number which did not work for me as system uses UTF-16 code. Therefore I browsed UTF-16 code for all UTF-16 character. Here is the module :

void utfchars()
{
 int i, a, b, x;
 ConsoleKeyInfo z;
  do
  {
   a = 0; b = 0; Console.Clear();
    for (i = 1; i <= 10000; i++)
    {
     if (b == 20)
     {
      b = 0;
      a = a + 1;
     }
    Console.SetCursorPosition((a * 15) + 1, b + 1);
    Console.Write("{0} == {1}", i, (char)i);
   b = b+1;
   if (i % 100 == 0)
  {
 Console.Write("\n\t\t\tPress any key to continue {0}", b);
 a = 0; b = 0;
 Console.ReadKey(true); Console.Clear();
 }
}
Console.Write("\n\n\n\n\n\n\n\t\t\tPress any key to Repeat and E to exit");
z = Console.ReadKey();
if (z.KeyChar == 'e' || z.KeyChar == 'E') Environment.Exit(0);
} while (1 == 1);
}

Regex to match only letters

Use a character set: [a-zA-Z] matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+ matches one or more letters and ^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively).

If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]. Or you use predefined character classes like the Unicode character property class \p{L} that describes the Unicode characters that are letters.

Regex any ASCII character

Since US-ASCII characters are in the byte range of 0x00–0x7F (0–127):

xxx[\x00-\x7F]+xxx

Create auto-numbering on images/figures in MS Word

I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

  1. Select all text in your document (easiest way is to press ctrl-a)
  2. Press F9, this command tells Word to update all fields in the selection.

Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

Convert java.util.date default format to Timestamp in Java

You can use

  long startTime = date.getTime() * 1000000;;
  long estimatedTime = System.nanoTime() - startTime;

To get time in nano.

Java Docs

How to remove specific object from ArrayList in Java?

    ArrayTest obj=new ArrayTest(1);
    test.add(obj);
    ArrayTest obj1=new ArrayTest(2);
    test.add(obj1);
    ArrayTest obj2=new ArrayTest(3);
    test.add(obj2);

    test.remove(object of ArrayTest);

you can specify how you control each object.

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

How to set a Fragment tag by code?

You can add the tag as a property for the Fragment arguments. It will be automatically restored if the fragment is destroyed and then recreated by the OS.

Example:-

    final Bundle args = new Bundle();
    args.putString("TAG", "my tag");
    fragment.setArguments(args);

Convert Data URI to File then append to FormData

I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:

var dataURL = canvas.toDataURL("image/jpeg");

var name = "image.jpg";
var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)

However, this doesn't come without its problems.

npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.

As an alternative, you can install the packages locally as well as globally.

For additional information, see

Define: What is a HashSet?

    1. A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here

    2. HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here

  1. There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

The HashSet class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.

The only catch of HashSet is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet into a List and iterate through that. Take a look here

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

Conditional WHERE clause in SQL Server

This seemed easier to think about where either of two parameters could be passed into a stored procedure. It seems to work:

SELECT * 
FROM x 
WHERE CONDITION1
AND ((@pol IS NOT NULL AND x.PolicyNo = @pol) OR (@st IS NOT NULL AND x.State = @st))
AND OTHERCONDITIONS

Show loading gif after clicking form submit using jQuery

What about an onclick function:

    <form id="form">
    <input type="text" name="firstInput">
    <button type="button" name="namebutton" 
           onClick="$('#gif').css('visibility', 'visible');
                    $('#form').submit();">
    </form>

Of course you can put this in a function and then trigger it with an onClick

Java Multiple Inheritance

There are two fundamental approaches to combining objects together:

  • The first is Inheritance. As you have already identified the limitations of inheritance mean that you cannot do what you need here.
  • The second is Composition. Since inheritance has failed you need to use composition.

The way this works is that you have an Animal object. Within that object you then add further objects that give the properties and behaviors that you require.

For example:

  • Bird extends Animal implements IFlier
  • Horse extends Animal implements IHerbivore, IQuadruped
  • Pegasus extends Animal implements IHerbivore, IQuadruped, IFlier

Now IFlier just looks like this:

 interface IFlier {
     Flier getFlier();
 }

So Bird looks like this:

 class Bird extends Animal implements IFlier {
      Flier flier = new Flier();
      public Flier getFlier() { return flier; }
 }

Now you have all the advantages of Inheritance. You can re-use code. You can have a collection of IFliers, and can use all the other advantages of polymorphism, etc.

However you also have all the flexibility from Composition. You can apply as many different interfaces and composite backing class as you like to each type of Animal - with as much control as you need over how each bit is set up.

Strategy Pattern alternative approach to composition

An alternative approach depending on what and how you are doing is to have the Animal base class contain an internal collection to keep the list of different behaviors. In that case you end up using something closer to the Strategy Pattern. That does give advantages in terms of simplifying the code (for example Horse doesn't need to know anything about Quadruped or Herbivore) but if you don't also do the interface approach you lose a lot of the advantages of polymorphism, etc.

How to read numbers separated by space using scanf

It should be as simple as using a list of receiving variables:

scanf("%i %i %i", &var1, &var2, &var3);

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

RegEx for validating an integer with a maximum length of 10 characters

[^0-9][+-]?[0-9]{1,10}[^0-9]

In words: Optional + or - followed by a digit, repeated one up to ten times. Note that most libraries have a shortcut for a digit: \d, hence the above could also be written as: \d{1,10}.

SQL Server: Make all UPPER case to Proper Case/Title Case

Recently had to tackle this and came up with the following after nothing quite hit everything I wanted. This will do an entire sentence, cases for special word handling. We also had issues with single character 'words' that a lot of the simpler methods handle but not the more complicated methods. Single return variable, no loops or cursors either.

CREATE FUNCTION ProperCase(@Text AS NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS BEGIN

    DECLARE @return NVARCHAR(MAX)

    SELECT @return = COALESCE(@return + ' ', '') + Word FROM (
         SELECT CASE
            WHEN LOWER(value) = 'llc' THEN UPPER(value)
            WHEN LOWER(value) = 'lp' THEN UPPER(value) --Add as many new special cases as needed
            ELSE
               CASE WHEN LEN(value) = 1
               THEN UPPER(value)
               ELSE UPPER(LEFT(value, 1)) + (LOWER(RIGHT(value, LEN(value) - 1)))
              END
            END AS Word
         FROM STRING_SPLIT(@Text, ' ')
     ) tmp

     RETURN @return
END

Database cluster and load balancing

Database clustering is a bit of an ambiguous term, some vendors consider a cluster having two or more servers share the same storage, some others call a cluster a set of replicated servers.

Replication defines the method by which a set of servers remain synchronized without having to share the storage being able to be geographically disperse, there are two main ways of going about it:

  • master-master (or multi-master) replication: Any server can update the database. It is usually taken care of by a different module within the database (or a whole different software running on top of them in some cases).

    Downside is that it is very hard to do well, and some systems lose ACID properties when in this mode of replication.

    Upside is that it is flexible and you can support the failure of any server while still having the database updated.

  • master-slave replication: There is only a single copy of authoritative data, which is the pushed to the slave servers.

    Downside is that it is less fault tolerant, if the master dies, there are no further changes in the slaves.

    Upside is that it is easier to do than multi-master and it usually preserve ACID properties.

Load balancing is a different concept, it consists distributing the queries sent to those servers so the load is as evenly distributed as possible. It is usually done at the application layer (or with a connection pool). The only direct relation between replication and load balancing is that you need some replication to be able to load balance, else you'd have a single server.

Forward slash in Java Regex

Double escaping is required when presented as a string.

Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.

how to use concatenate a fixed string and a variable in Python

I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

Python: No acceptable C compiler found in $PATH when installing python

sudo apt install build-essential is the command

But if you get the "the package can be found" kind of error, Run

  • sudo apt update first
  • then sudo apt install build-essential

This worked for me.

Case statement in MySQL

This should work:

select 
  id
  ,action_heading
  ,case when action_type='Income' then action_amount else 0 end
  ,case when action_type='Expense' then expense_amount else 0 end
from tbl_transaction

How to vertically align into the center of the content of a div with defined width/height?

margin: all_four_margin

by providing 50% to all_four_margin will place the element at the center

style="margin: 50%"

you can apply it for following too

margin: top right bottom left

margin: top right&left bottom

margin: top&bottom right&left

by giving appropriate % we get the element wherever we want.

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

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

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

How to remove specific session in asp.net?

you can use Session.Remove() method; Session.Remove

Session.Remove("yourSessionName");

php implode (101) with quotes

If you want to use loops you can also do:

$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

Node.js connect only works on localhost

Working for me with this line (simply add --listen when running) :

node server.js -p 3000 -a : --listen 192.168.1.100

Hope it helps...

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()

Subtract two dates in Java

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date2));

long diff = d2.getTime() - d1.getTime();

System.out.println("Difference between  " + d1 + " and "+ d2+" is "
        + (diff / (1000 * 60 * 60 * 24)) + " days.");

Allow only numbers to be typed in a textbox

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

Check if all elements in a list are identical

def allTheSame(i):
    j = itertools.groupby(i)
    for k in j: break
    for k in j: return False
    return True

Works in Python 2.4, which doesn't have "all".

onClick function of an input type="button" not working

You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />
                                     ----------------------

Why do I get a "permission denied" error while installing a gem?

Your Ruby is installed in /usr/local/Cellar/ruby/....

That is a restricted path and can only be written to when you use elevated privileges, either by running as root or by using sudo. I won't recommend you run things as root since you don't understand how paths and permissions work. You can use sudo gem install jekyll, which will temporarily elevate your permissions, giving your command the rights needed to write to that directory.

However, I'd recommend you give serious thought into NOT doing that, and instead use your RVM to install Ruby into your own home directory, where you'll automatically be able to install Rubies and gems without permission issues. See the directions for installing into a local RVM sandbox in "Single-User installations".

Because you have RVM in your ~/.bash_profile, but it doesn't show up in your Gem environment listing, I suspect you either haven't followed the directions for installing RVM correctly, or you haven't used the all-important command:

rvm use 2.0.0 --default

to configure a default Ruby.

For most users, the "Single-User installation" is the way to go. If you have to use sudo with that configuration you've done something wrong.

Conversion between UTF-8 ArrayBuffer and String

The latest answers to these type of questions (using nowadays methods) is here: Converting between strings and ArrayBuffers

Adobe Reader Command Line Reference

Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n

string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe"; 
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();

What is the equivalent of "none" in django templates?

{% if profile.user.first_name %} works (assuming you also don't want to accept '').

if in Python in general treats None, False, '', [], {}, ... all as false.

symfony2 : failed to write cache directory

I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine

rm -rf app/cache/*
rm -rf app/logs/*

How to print instances of a class using print()?

If you're in a situation like @Keith you could try:

print(a.__dict__)

It goes against what I would consider good style but if you're just trying to debug then it should do what you want.

How to simulate "Press any key to continue?"

Also you can use getch() from conio.h. Just like this:

...includes, defines etc
void main()
{
//operator
getch(); //now this function is waiting for any key press. When you have pressed its     just     //finish and next line of code will be called
}

So, because UNIX does not have conio.h, we can simulate getch() by this code (but this code already written by Vinary, my fail):

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch( ) {
  struct termios oldt,
             newt;
  int            ch;
  tcgetattr( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
  return ch;
}

How to find length of a string array?

Well, in this case the car variable will be null, so dereferencing it (as you do when you access car.length) will throw a NullPointerException.

In fact, you can't access that variable at all until some value has definitely been assigned to it - otherwise the compiler will complain that "variable car might not have been initialized".

What is it you're trying to do here (it's not clear to me exactly what "solution" you're looking for)?

Putting HTML inside Html.ActionLink(), plus No Link Text?

Just use Url.Action instead of Html.ActionLink:

<li id="home_nav"><a href="<%= Url.Action("ActionName") %>"><span>Span text</span></a></li>

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

Changing Font Size For UITableView Section Headers

With this method you can set font size, font style and Header background also. there are have 2 method for this

First Method

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
        UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
        header.backgroundView.backgroundColor = [UIColor darkGrayColor];
        header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
        [header.textLabel setTextColor:[UIColor whiteColor]];
    }

Second Method

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
//    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
    myLabel.text = [NSString stringWithFormat:@"   %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];

    myLabel.backgroundColor=[UIColor blueColor];
    myLabel.textColor=[UIColor whiteColor];
    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];
    return headerView;
}

How to find substring inside a string (or how to grep a variable)?

Well, what about something like this:

PS3="Select database or <Q> to quit: "
select DB in db1 db2 db3; do
   [ "${REPLY^*}" = 'Q' ] && break
   echo "Should backup $DB..."
done

Is PowerShell ready to replace my Cygwin shell on Windows?

The cmdlets in PowerShell are very nice and work reliably. Their object-orientedness appeals to me a lot since I'm a Java/C# developer, but it's not at all a complete set. Since it's object oriented, it's missed out on a lot of the text stream maturity of the POSIX tool set (awk and sed to name a few).

The best answer I've found to the dilemma of loving OO techniques and loving the maturity in the POSIX tools is to use both! One great aspect of PowerShell is that it does an excellent job piping objects to standard streams. PowerShell by default uses an object pipeline to transport its objects around. These aren't the standard streams (standard out, standard error, and standard in). When PowerShell needs to pass output to a standard process that doesn't have an object pipeline, it first converts the objects to a text stream. Since it does this so well, PowerShell makes an excellent place to host POSIX tools!

The best POSIX tool set is GnuWin32. It does take more than 5 seconds to install, but it's worth the trouble, and as far as I can tell, it doesn't modify your system (registry, c:\windows\* folders, etc.) except copying files to the directories you specify. This is extra nice because if you put the tools in a shared directory, many people can access them concurrently.

GnuWin32 Installation Instructions

Download and execute the exe (it's from the SourceForge site) pointing it to a suitable directory (I'll be using C:\bin). It will create a GetGnuWin32 directory there in which you will run download.bat, then install.bat (without parameters), after which, there will be a C:\bin\GetGnuWin32\gnuwin32\bin directory that is the most useful folder that has ever existed on a Windows machine. Add that directory to your path, and you're ready to go.

Android scale animation on view

Use this method (No need to xml file)

If you want scale to quarter(half x,half y)

view.animate().scaleX(0.5f).scaleY(0.5f)

If you want scale and move to bottom right

view.animate().scaleX(0.5f).scaleY(0.5f)
        .translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())

If you want move to top use (-view.height/4) and for left (-view.width/4)

If you want do something after animation ends use withEndAction(Runnable runnable) function.

You can use some other property like alpha and rotation

Full code

view.animate()
      .scaleX(0.5f).scaleY(0.5f)//scale to quarter(half x,half y)
      .translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())// move to bottom / right
      .alpha(0.5f) // make it less visible
      .rotation(360f) // one round turns
      .setDuration(1000) // all take 1 seconds
      .withEndAction(new Runnable() {
           @Override
           public void run() {
              //animation ended
           }
      });

Open a PDF using VBA in Excel

If it's a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

how to save and read array of array in NSUserdefaults in swift?

Here is an example of reading and writing a list of objects of type SNStock that implements NSCoding - we have an accessor for the entire list, watchlist, and two methods to add and remove objects, that is addStock(stock: SNStock) and removeStock(stock: SNStock).

import Foundation

class DWWatchlistController {

  private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"

  private let userDefaults: NSUserDefaults

  private(set) var watchlist:[SNStock] {

    get {
      if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
        if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
          return watchlist as! [SNStock]
        }
      }
      return []
    }

    set(watchlist) {
      let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
      userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
      userDefaults.synchronize()
    }
  }

  init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
  }

  func addStock(stock: SNStock) {
    var watchlist = self.watchlist
    watchlist.append(stock)
    self.watchlist = watchlist
  }

  func removeStock(stock: SNStock) {
    var watchlist = self.watchlist
    if let index = find(watchlist, stock) {
      watchlist.removeAtIndex(index)
      self.watchlist = watchlist
    }
  }

}

Remember that your object needs to implement NSCoding or else the encoding won't work. Here is what SNStock looks like:

import Foundation

class SNStock: NSObject, NSCoding
{
  let ticker: NSString
  let name: NSString

  init(ticker: NSString, name: NSString)
  {
    self.ticker = ticker
    self.name = name
  }

  //MARK: NSCoding

  required init(coder aDecoder: NSCoder) {
    self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
    self.name = aDecoder.decodeObjectForKey("name") as! NSString
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(ticker, forKey: "ticker")
    aCoder.encodeObject(name, forKey: "name")
  }

  //MARK: NSObjectProtocol

  override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? SNStock {
      return self.ticker == object.ticker &&
        self.name == object.name
    } else {
      return false
    }
  }

  override var hash: Int {
    return ticker.hashValue
  }
}

Hope this helps!

Apply pandas function to column to create multiple new columns?

In 2020, I use apply() with argument result_type='expand'

>>> appiled_df = df.apply(lambda row: fn(row.text), axis='columns', result_type='expand')
>>> df = pd.concat([df, appiled_df], axis='columns')

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For all those people stuck with this problem, but still couldn't solve it: I stumbled upon the same error and found the _id field being empty.

I described it here in more detail. Still have not found a solution except changing the fields in _id to not-ID fields which is a dirty hack to me. I'm probably going to file a bug report for mongoose. Any help would be appreciated!

Edit: I updated my thread. I filed a ticket and they confirmed the missing _id problem. It is going to be fixed in the 4.x.x version which has a release candidate available right now. The rc is not recommended for productive use!

Function is not defined - uncaught referenceerror

Clearing Cache solved the issue for me or you can open it in another browser

index.js

function myFun() {
    $('h2').html("H999999");
}

index.jsp

<html>
<head>
    <title>Reader</title>
</head>
<body>
<h2>${message}</h2>
<button id="hi" onclick="myFun();" type="submit">Hi</button>
</body>
</html>

Returning a value even if no result

if you want both always a return value but never a null value you can combine count with coalesce :

select count(field1), coalesce(field1,'any_other_default_value') from table;

that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null

Encrypt and decrypt a String in java

I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??

This depends strongly on the crypto algorithm you use:

  • One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.
  • Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

Chrome / Safari not filling 100% height of flex parent

I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.

I managed to get it to work by adding both the height and min-height properties to the CSS class.

The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: 100px;
  height: 100px;
}

Hope this helps!

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How can you encode a string to Base64 in JavaScript?

Here is a LIVE DEMO of atob() and btoa() JS built in functions:

<!DOCTYPE html>
<html>
  <head>
    <style>
      textarea{
        width:30%;
        height:100px;
      }
    </style>
    <script>
      // encode string to base64
      function encode()
      {
        var txt = document.getElementById("txt1").value;
        var result = btoa(txt);
        document.getElementById("txt2").value = result;
      }
      // decode base64 back to original string
      function decode()
      {
        var txt = document.getElementById("txt3").value;
        var result = atob(txt);
        document.getElementById("txt4").value = result;
      }
    </script>
  </head>
  <body>
    <div>
      <textarea id="txt1">Some text to decode
      </textarea>
    </div>
    <div>
      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
    </div>
    <div>
      <textarea id="txt2">
      </textarea>
    </div>
    <br/>
    <div>
      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>
    </div>
    <div>
      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
    </div>
    <div>
      <textarea id="txt4">
      </textarea>
    </div>
  </body>
</html>

Updating GUI (WPF) using a different thread

Use Following Method to Update GUI.

     Public Void UpdateUI()
     {
         //Here update your label, button or any string related object.

         //Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));    
         Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
     }

Keep it in Mind when you use this method at that time do not Update same object direct from dispatcher thread otherwise you get only that updated string and this method is helpless/useless. If still not working then Comment that line inside method and un-comment commented one both have nearly same effect just different way to access it.

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

I will try to give the solution that worked for me. It seems that different set of problems can lead to this situation.

32 bit software works in 64 bit OS. I installed anaconda-3 (32 bit) in my 64 bit OS. It was working perfectly fine. I decided to install tensorflow in my machine and it wouldn't install at first. I was using conda environment to install tensorflow and got this error.

Solution is if you are running 64 bit OS, install 64 bit anaconda and if 32 bit OS then 32 bit anaconda. Then follow the standard procedure mentioned in tensorflow website for windows (anaconda installation). This made it possible to install tensorflow without any problem.

addID in jQuery?

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

Increment counter with loop

Try the following:

<c:set var="count" value="0" scope="page" />

//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>

How can I search an array in VB.NET?

If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.

How do I use vim registers?

I was pleased when I discovered the 0 register. If you yank text without assigning it to a particular register, then it will be assigned to the 0 register, as well as being saved in the default " register. The difference between the 0 and " registers is that 0 is only populated with yanked text, whereas the default register is also populated with text deleted using d/D/x/X/c/C/s/S commands.

I find this useful when I want to copy some text, delete something and replace it with the copied text. The following steps illustrate an example:

  • Yank the text you want to copy with y[motion] - this text is saved in " and 0 registers
  • Delete the text you want to replace with d[motion] - this text is saved in " register
  • Paste the yanked text with "0p

where " is the command to use a register for the next command.

On the final step, if you were to paste from the default register (with p), it would use the text that you had just deleted (probably not what you intended).

Note that p or P pastes from the default register. The longhand equivalent would be ""p (or ""P) and "0 holds the last yank, "1holds the last delete or change.

For more info see :help registers.

JavaScript Chart.js - Custom data formatting to display on tooltip

This works perfectly fine with me. It takes label and format the value.

options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {

                    let label = data.labels[tooltipItem.index];
                    let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return ' ' + label + ': ' + value + ' %';

                }
            }
        }
    }

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

Add BrowserModule to imports: [] in @NgModule() if it's the root module (AppModule), otherwise the CommonModule.

// older Angular versions
// import {BrowserModule, CommonModule} from '@angular/common';

import { BrowserModule } from '@angular/platform-browser'
..
..
@NgModule({
  imports: [BrowserModule, /* or CommonModule */],
  ..
})

How to convert a Java 8 Stream to an Array?

Using the toArray(IntFunction<A[]> generator) method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.

However, if the returned array's type is not important, simply using the toArray() method is both easier and shorter. For example:

    Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
    System.out.printf("%s, %s, %s!", args.toArray());

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

Don't reload application when orientation changes

Just add this to your AndroidManifest.xml

<activity android:screenOrientation="landscape">

I mean, there is an activity tag, add this as another parameter. In case if you need portrait orientation, change landscape to portrait. Hope this helps.

The VMware Authorization Service is not running

This problem was solved for me by running VMware workstation as Windows administrator. From the start menu right click on the VMware workstation, then select "Run as Administrator"

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

How to use switch statement inside a React component?

That's happening, because switch statement is a statement, but here javascript expects an expression.

Although, it's not recommended to use switch statement in a render method, you can use self-invoking function to achieve this:

render() {
    // Don't forget to return a value in a switch statement
    return (
        <div>
            {(() => {
                switch(...) {}
            })()}
        </div>
    );
}

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

Why maven? What are the benefits?

Maven advantages over ant are quite a few. I try to summarize them here.

Convention over Configuration
Maven uses a distinctive approach for the project layout and startup, that makes easy to just jump in a project. Usually it only takes the checkount and the maven command to get the artifacts of the project.

Project Modularization
Project conventions suggest (or better, force) the developer to modularize the project. Instead of a monolithic project you are often forced to divide your project in smaller sub components, which make it easier debug and manage the overall project structure

Dependency Management and Project Lifecycle
Overall, with a good SCM configuration and an internal repository, the dependency management is quite easy, and you are again forced to think in terms of Project Lifecycle - component versions, release management and so on. A little more complex than the ant something, but again, an improvement in quality of the project.

What is wrong with maven?
Maven is not easy. The build cycle (what gets done and when) is not so clear within the POM. Also, some issue arise with the quality of components and missing dependencies in public repositories.
The best approach (to me) is to have an internal repository for caching (and keeping) dependencies around, and to apply to release management of components. For projects bigger than the sample projects in a book, you will thank maven before or after

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

I can not find my.cnf on my windows computer

Windows 7 location is: C:\Users\All Users\MySQL\MySQL Server 5.5\my.ini

For XP may be: C:\Documents and Settings\All Users\MySQL\MySQL Server 5.5\my.ini

At the tops of these files are comments defining where my.cnf can be found.

python ignore certificate validation urllib2

A more explicit example, built on Damien's code (calls a test resource at http://httpbin.org/). For python3. Note that if the server redirects to another URL, uri in add_password has to contain the new root URL (it's possible to pass a list of URLs, also).

import ssl    
import urllib.parse
import urllib.request

def get_resource(uri, user, passwd=False):
    """
    Get the content of the SSL page.
    """
    uri = 'https://httpbin.org/basic-auth/user/passwd'
    user = 'user'
    passwd = 'passwd'

    context = ssl.create_default_context()
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE

    password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, uri, user, passwd)

    auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

    opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))

    urllib.request.install_opener(opener)

    return urllib.request.urlopen(uri).read()

Not showing placeholder for input type="date" field

HTML:

<div>
    <input class="ui-btn ui-btn-icon-right ui-corner-all ui-icon-calendar ui-shadow" id="inputDate" type="date"/>
    <h3 id="placeholder-inputDate">Date Text</h3>
</div>

JavaScript:

$('#inputDate').ready(function () {
$('#placeholder-inputDate').attr('style'
    , 'top: ' + ($('#placeholder-inputDate').parent().position().top + 10)
    + 'px; left: ' + ($('#placeholder-inputDate').parent().position().left + 0) + 'px; position: absolute;');
$('#inputDate').attr('style'
    , 'width: ' + ($('#placeholder-inputDate').width() + 32) + 'px;');
});

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

It seems that the problem with IE comes when you try and access the iframe via the document.frames object - if you store a reference to the created iframe in a variable then you can access the injected iframe via the variable (my_iframe in the code below).

I've gotten this to work in IE6/7/8

var my_iframe;
var iframeId = "my_iframe_name"
if (navigator.userAgent.indexOf('MSIE') !== -1) {
  // IE wants the name attribute of the iframe set
  my_iframe = document.createElement('<iframe name="' + iframeId + '">');
} else {
  my_iframe = document.createElement('iframe');
}

iframe.setAttribute("src", "javascript:void(0);");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameBorder", "0");
iframe.setAttribute("name", iframeId);

var is = iframe.style;
is.border = is.width = is.height = "0px";

if (document.body) {
  document.body.appendChild(my_iframe);
} else {
  document.appendChild(my_iframe);
}

How to Join to first row

try this

SELECT
   Orders.OrderNumber,
   LineItems.Quantity, 
   LineItems.Description
FROM Orders
   INNER JOIN (
      SELECT
         Orders.OrderNumber,
         Max(LineItem.LineItemID) AS LineItemID
       FROM Orders 
          INNER JOIN LineItems
          ON Orders.OrderNumber = LineItems.OrderNumber
       GROUP BY Orders.OrderNumber
   ) AS Items ON Orders.OrderNumber = Items.OrderNumber
   INNER JOIN LineItems 
   ON Items.LineItemID = LineItems.LineItemID

How to style child components from parent component's CSS file?

As the internet updates I've come across a solution.

First some caveats.

  1. Still don't do it. To clarify, I wouldn't plan on child components allowing you to style them. SOC. If you as the component designer want to allow this then all the more power to you.
  2. If your child doesn't live in the shadow dom then this won't work for you.
  3. If you have to support a browser that can't have a shadow dom then this also won't work for you.

First, mark your child component's encapsulation as shadow so it renders in the actual shadow dom. Second, add the part attribute to the element you wish to allow the parent to style. In your parent's component stylesheet you can use the ::part() method to access

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

How can I set a custom baud rate on Linux?

You can set a custom baud rate using the stty command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:

stty -F /dev/ttyX0 567890

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

Check for column name in a SqlDataReader object

You can also call GetSchemaTable() on your DataReader if you want the list of columns and you don't want to have to get an exception...

TypeError: $ is not a function when calling jQuery function

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...

Making a button invisible by clicking another button in HTML

To get an element by its ID, use this:

document.getElementById("p2")

Instead of:

document.getElementsByName("p2")

So the final product would be:

document.getElementsById("p2").style.visibility = "hidden";

How to change color of ListView items on focus and on click

In your main.xml include the following in your ListView:

android:drawSelectorOnTop="false"

android:listSelector="@android:color/darker_gray"

Get user info via Google API

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture

However, location is not returned. New YouTube accounts don't have YouTube specific usernames

Return row of Data Frame based on value in a column - R

Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]

> df[which.min(df$Amount),]
  Name Amount
2    B    120

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/

Full width layout with twitter bootstrap

The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :

.container{
  max-width:100%;
  padding:0;
}

sqlite3.OperationalError: unable to open database file

I faced the same problem on Windows 7. My database name was test and I got the error:

self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file

I replaced test with test.db and and all went smooth.

When to use a linked list over an array/array list?

To add to the other answers, most array list implementations reserve extra capacity at the end of the list so that new elements can be added to the end of the list in O(1) time. When the capacity of an array list is exceeded, a new, larger array is allocated internally, and all the old elements are copied over. Usually, the new array is double the size of the old one. This means that on average, adding new elements to the end of an array list is an O(1) operation in these implementations. So even if you don't know the number of elements in advance, an array list may still be faster than a linked list for adding elements, as long as you are adding them at the end. Obviously, inserting new elements at arbitrary locations in an array list is still an O(n) operation.

Accessing elements in an array list is also faster than a linked list, even if the accesses are sequential. This is because array elements are stored in contiguous memory and can be cached easily. Linked list nodes can potentially be scattered over many different pages.

I would recommend only using a linked list if you know that you're going to be inserting or deleting items at arbitrary locations. Array lists will be faster for pretty much everything else.

jQuery AJAX submit form

Simple version (does not send images)

<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
    (function($){
        $("body").on("submit", ".my-form", function(e){
            e.preventDefault();
            var form = $(e.target);
            $.post( form.attr("action"), form.serialize(), function(res){
                console.log(res);
            });
        });
    )(jQuery);
</script>

Copy and paste ajaxification of a form or all forms on a page

It is a modified version of Alfrekjv's answer

  • It will work with jQuery >= 1.3.2
  • You can run this before the document is ready
  • You can remove and re-add the form and it will still work
  • It will post to the same location as the normal form, specified in the form's "action" attribute

JavaScript

jQuery(document).submit(function(e){
    var form = jQuery(e.target);
    if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
        e.preventDefault();
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: form.serialize(), // serializes the form's elements.
            success: function(data) {
                console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
            }
        });
    }
});

I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.

Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.

To support buttons you can capture the actual button click instead of the submit.

jQuery(document).click(function(e){
    var self = jQuery(e.target);
    if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
        e.preventDefault();
        var form = self.closest('form'), formdata = form.serialize();
        //add the clicked button to the form data
        if(self.attr('name')){
            formdata += (formdata!=='')? '&':'';
            formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
        }
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: formdata, 
            success: function(data) {
                console.log(data);
            }
        });
    }
});

On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH for php

PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //is ajax
}

Embedding VLC plugin on HTML page

test.html is will be helpful for how to use VLC WebAPI.

test.html is located in the directory where VLC was installed.

e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html

The following code is a quote from the test.html.

HTML:

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
  <param name="MRL" value="" />
  <param name="ShowDisplay" value="True" />
  <param name="AutoLoop" value="False" />
  <param name="AutoPlay" value="False" />
  <param name="Volume" value="50" />
  <param name="toolbar" value="true" />
  <param name="StartTime" value="0" />
  <EMBED pluginspage="http://www.videolan.org"
    type="application/x-vlc-plugin"
    version="VideoLAN.VLCPlugin.2"
    width="640"
    height="360"
    toolbar="true"
    loop="false"
    text="Waiting for video"
    name="vlc">
  </EMBED>
</object>

JavaScript:

You can get vlc object from getVLC().
It works on IE 10 and Chrome.

function getVLC(name)
{
    if (window.document[name])
    {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

var vlc = getVLC("vlc");

// do something.
// e.g. vlc.playlist.play();

Change image source with JavaScript

 <script type="text/javascript">
        function changeImage(a) {
    var picName=a.substring(1,a.length-1);
            document.getElementById("image").src=picName;
        }
 </script>

 <div id="main_img">
     <img id="image" src="app.jpg">
 </div>

 <div id="thumb_img">
     <img src='app.jpg'  onclick="changeImage('+5steps.jpg+');">
     <img src='5steps.jpg'  onclick="changeImage('+award.png+');">
     <img src='award.png'  onclick="changeImage('+app.jpg+');">
 </div>

Use the above code by placing this html file and pics(take care in namings, beacause I have given the above code with my pic names) in same folder you will get...

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Coming here from first Google hit:

You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1.

On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1 the warning will go away.

It's probably because you are building a gem from source and the gemspec shells out to git, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git but addressing that is for another day :)

My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Python: Making a beep noise

Linux.

$ apt-get install beep

$ python
>>> os.system("beep -f 555 -l 460")

OR

$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

How can I view an object with an alert()

Depending on which property you are interested in:

alert(product.ProductName);
alert(product.UnitPrice);
alert(product.Stock);

What is the hamburger menu icon called and the three vertical dots icon called?

At eBay it’s the kabob.

Also heard it called the snowman or sushi roll.

How to get time in milliseconds since the unix epoch in Javascript?

Date.now() returns a unix timestamp in milliseconds.

_x000D_
_x000D_
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
_x000D_
_x000D_

Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:

_x000D_
_x000D_
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
_x000D_
_x000D_

Python function attributes - uses and abuses

I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)

class Foo(WebService):
    @webmethod
    def bar(self, arg1, arg2):
         ...

then I can define

def webmethod(func):
    func.is_webmethod = True
    return func

Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.

How to compare character ignoring case in primitive types

Generic methods to compare a char at a position between 2 strings with ignore case.

public static boolean isEqualIngoreCase(char one, char two){
    return Character.toLowerCase(one)==Character .toLowerCase(two);
}

public static boolean isEqualStringCharIgnoreCase(String one, String two, int position){
    char oneChar = one.charAt(position);
    char twoChar = two.charAt(position);
    return isEqualIngoreCase(oneChar, twoChar);
}

Function call

boolean isFirstCharEqual = isEqualStringCharIgnoreCase("abc", "ABC", 0)

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

Find the index of a dict within a list, by matching the dict's value

A simple readable version is

def find(lst, key, value):
    for i, dic in enumerate(lst):
        if dic[key] == value:
            return i
    return -1

What is ".NET Core"?

.NET Core is an open source and cross platform version of .NET. Microsoft products, besides the great abilities that they have, were always expensive for usual users, especially end users of products that has been made by .NET technologies.

Most of the low-level customers prefer to use Linux as their OS and before .NET Core they would not like to use Microsoft technologies, despite the great abilities of them. But after .NET Core production, this problem is solved completely and we can satisfy our customers without considering their OS, etc.

Add text to Existing PDF using Python

If you're on Windows, this might work:

PDF Creator Pilot

There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:

Using Python as PDF Editing and Processing Framework

Get the year from specified date php

<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I have faced same issue a couple of days ago while updating the database. In my case, there was few new non nullable columns added for maintenance which was not supplied in the code which is causing the exception. I figure out those fields and supplied values for them and its resolved.

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How to run .jar file by double click on Windows 7 64-bit?

change the default application for JAR files from java.exe to javaw.exe from your JAVA_HOME/bin folder.

This is because, java.exe is console application only, but JAR file needs a window rendered execution. Since javaw.exe is a window application, it is preferred for the execution of JAR files.

An alternative to this is that to some extent you can use command prompt to run your JAR files by simply using java keyword with -jar attrib.

What is std::move(), and when should it be used?

You can use move when you need to "transfer" the content of an object somewhere else, without doing a copy (i.e. the content is not duplicated, that's why it could be used on some non-copyable objects, like a unique_ptr). It's also possible for an object to take the content of a temporary object without doing a copy (and save a lot of time), with std::move.

This link really helped me out :

http://thbecker.net/articles/rvalue_references/section_01.html

I'm sorry if my answer is coming too late, but I was also looking for a good link for the std::move, and I found the links above a little bit "austere".

This puts the emphasis on r-value reference, in which context you should use them, and I think it's more detailed, that's why I wanted to share this link here.

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

A full list of all the new/popular databases and their uses?

There are graph databases like:

A graph database stores data as nodes and relationships/edges.This is a good fit for semi-structured data, interconnected information and domains with deep relationships/traversal, for example social networks and knowledge representation. The data model is highly flexible and "whiteboard friendly". The underlying data model of the semantic web, RDF, is also a (labeled, directed multi-)graph.

Other stackoverflow threads with information on graph databases:

Passing arrays as parameters in bash

An easy way to pass several arrays as parameter is to use a character-separated string. You can call your script like this:

./myScript.sh "value1;value2;value3" "somethingElse" "value4;value5" "anotherOne"

Then, you can extract it in your code like this:

myArray=$1
IFS=';' read -a myArray <<< "$myArray"

myOtherArray=$3
IFS=';' read -a myOtherArray <<< "$myOtherArray"

This way, you can actually pass multiple arrays as parameters and it doesn't have to be the last parameters.

How to ignore ansible SSH authenticity checking?

I found the answer, you need to set the environment variable ANSIBLE_HOST_KEY_CHECKING to False. For example:

ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook ...

jQuery removeClass wildcard

A generic function that remove any class starting with begin:

function removeClassStartingWith(node, begin) {
    node.removeClass (function (index, className) {
        return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');
    });
}

http://jsfiddle.net/xa9xS/2900/

_x000D_
_x000D_
var begin = 'color-';_x000D_
_x000D_
function removeClassStartingWith(node, begin) {_x000D_
    node.removeClass (function (index, className) {_x000D_
        return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');_x000D_
    });_x000D_
}_x000D_
_x000D_
removeClassStartingWith($('#hello'), 'color-');_x000D_
_x000D_
console.log($("#hello")[0].className);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello" class="color-red color-brown foo bar"></div>
_x000D_
_x000D_
_x000D_

How to avoid using Select in Excel VBA

Working with the .Parent feature, this example shows how setting only one myRng reference enables dynamic access to the entire environment without any .Select, .Activate, .Activecell, .ActiveWorkbook, .ActiveSheet and so on. (There isn't any generic .Child feature.)

Sub ShowParents()
    Dim myRng As Range
    Set myRng = ActiveCell
    Debug.Print myRng.Address                    ' An address of the selected cell
    Debug.Print myRng.Parent.name                ' The name of sheet, where MyRng is in
    Debug.Print myRng.Parent.Parent.name         ' The name of workbook, where MyRng is in
    Debug.Print myRng.Parent.Parent.Parent.name  ' The name of application, where MyRng is in

    ' You may use this feature to set reference to these objects
    Dim mySh  As Worksheet
    Dim myWbk As Workbook
    Dim myApp As Application

    Set mySh = myRng.Parent
    Set myWbk = myRng.Parent.Parent
    Set myApp = myRng.Parent.Parent.Parent
    Debug.Print mySh.name, mySh.Cells(10, 1).Value
    Debug.Print myWbk.name, myWbk.Sheets.Count
    Debug.Print myApp.name, myApp.Workbooks.Count

    ' You may use dynamically addressing
    With myRng
        .Copy

        ' Pastes in D1 on sheet 2 in the same workbook, where the copied cell is
        .Parent.Parent.Sheets(2).Range("D1").PasteSpecial xlValues

        ' Or myWbk.Sheets(2).Range("D1").PasteSpecial xlValues

        ' We may dynamically call active application too
        .Parent.Parent.Parent.CutCopyMode = False

        ' Or myApp.CutCopyMode = False
    End With
End Sub

How can I make a JPA OneToOne relation lazy

In native Hibernate XML mappings, you can accomplish this by declaring a one-to-one mapping with the constrained attribute set to true. I am not sure what the Hibernate/JPA annotation equivalent of that is, and a quick search of the doc provided no answer, but hopefully that gives you a lead to go on.

how to rotate a bitmap 90 degrees

public static Bitmap RotateBitmap(Bitmap source, float angle)
{
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

To get Bitmap from resources:

Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);

PHP: get the value of TEXTBOX then pass it to a VARIABLE

You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

name = "name"

will only cause confusion IMO.

How to read the post request parameters using JavaScript

A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:

var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;

Then just access the JavaScript variable in the normal way.

Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.

HTML5 Number Input - Always show 2 decimal places

Solved following the suggestions and adding a piece of jQuery to force the format on integers:

parseFloat($(this).val()).toFixed(2)

How to convert string into float in JavaScript?

You can use this function. It will replace the commas with ' ' and then it will parseFlaot the value and after that it will again adjust the commas in value.

function convertToFloat(val) {
        if (val != '') {
            if (val.indexOf(',') !== -1)
                val.replace(',', '');
            val = parseFloat(val);
            while (/(\d+)(\d{3})/.test(val.toString())) {
                val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
            }
        }
        return val;
    }

how to initialize a char array?

This method uses the 'C' memset function, and is very fast (avoids a char-by-char loop).

const uint size = 65546;
char* msg = new char[size];
memset(reinterpret_cast<void*>(msg), 0, size);

Pandas read in table without headers

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

Solution

Use usecols and names parameters

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

Additional reading

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

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

So that you can retrieve your data by

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

instead of

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

Explain

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

Change color of Button when Mouse is over

As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.

How to use after we created the ButtonEx-class:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfEx="clr-namespace:WpfExtensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
    </Grid>
</Window>

ButtonEx.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfExtensions
{
    /// <summary>
    /// Standard button with extensions
    /// </summary>
    public partial class ButtonEx : Button
    {
        readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;

        public ButtonEx()
        {
            InitializeComponent();
        }

        public Brush HoverBackground
        {
            get { return (Brush)GetValue(HoverBackgroundProperty); }
            set { SetValue(HoverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
          "HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
    }
}

ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button

<Button x:Class="WpfExtensions.ButtonEx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
            x:Name="buttonExtension">
    <Button.Resources>
        <Style x:Key="FocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.

mysql select from n last rows

Might be a very late answer, but this is good and simple.

select * from table_name order by id desc limit 5

This query will return a set of last 5 values(last 5 rows) you 've inserted in your table

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Note: static synchronized methods and blocks work on the Class object.

public class MyClass {
   // locks MyClass.class
   public static synchronized void foo() {
// do something
   }

   // similar
   public static void foo() {
      synchronized(MyClass.class) {
// do something
      }
   }
}

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I had the problem that my new controls would not generate in the designer file when declared in the .ascx file. The problem was that i declared them in the code behind also. So deleting the declaration in the code behind solved my problem.

How to set-up a favicon?

you could take a look at the w3 how to, i think you will find it helpful

your link tag attribute should be rel="icon"

How to see query history in SQL Server Management Studio

The system doesn't record queries in that way. If you know you want to do that ahead of time though, you can use SQL Profiler to record what is coming in and track queries during the time Profiler is running.

How do you programmatically update query params in react-router?

Within the push method of hashHistory, you can specify your query parameters. For instance,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

You can check out this repository for additional examples on using history

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How to get an object's properties in JavaScript / jQuery?

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));

If Radio Button is selected, perform validation on Checkboxes

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

Java compile error: "reached end of file while parsing }"

It happens when you don't properly close the code block:

if (condition){
  // your code goes here*
  { // This doesn't close the code block

Correct way:

if (condition){
  // your code goes here
} // Close the code block

Bulk create model objects in django

for a single line implementation, you can use a lambda expression in a map

map(lambda x:MyModel.objects.get_or_create(name=x), items)

Here, lambda matches each item in items list to x and create a Database record if necessary.

Lambda Documentation

Java 8 NullPointerException in Collectors.toMap

public static <T, K, V> Collector<T, HashMap<K, V>, HashMap<K, V>> toHashMap(
        Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends V> valueMapper
)
{
    return Collector.of(
            HashMap::new,
            (map, t) -> map.put(keyMapper.apply(t), valueMapper.apply(t)),
            (map1, map2) -> {
                map1.putAll(map2);
                return map1;
            }
    );
}

public static <T, K> Collector<T, HashMap<K, T>, HashMap<K, T>> toHashMap(
        Function<? super T, ? extends K> keyMapper
)
{
    return toHashMap(keyMapper, Function.identity());
}

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

Class library is shared compiled code.

Shared project is shared source code.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

Schema::table is to modify an existing table, use Schema::create to create new.

Nodejs - Redirect url

It's possible to use:

res.redirect('your/404/path.html');

How can I get the current time in C#?

try this:

 string.Format("{0:HH:mm:ss tt}", DateTime.Now);

for further details you can check it out : How do you get the current time of day?

Is it possible to put a ConstraintLayout inside a ScrollView?

use NestedScrollView with viewport true is working good for me

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="700dp">

        </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

How To Launch Git Bash from DOS Command Line?

The answer by Endoro has aged and I'm unable to comment;

# if you want to launch from a batch file or the command line:

start "" "%ProgramFiles%\Git\bin\sh.exe" --login

Project has no default.properties file! Edit the project properties to set one

Project has no default.properties file! Edit the project properties to set one

best option is create new workspace import the project ,fix the project its work

Check if one date is between two dates

I have created customize function to validate given date is between two dates or not.

var getvalidDate = function(d){ return new Date(d) }

function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
    return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}

How to test if a string is basically an integer in quotes using Ruby

For more generalised cases (including numbers with decimal point), you can try the following method:

def number?(obj)
  obj = obj.to_s unless obj.is_a? String
  /\A[+-]?\d+(\.[\d]+)?\z/.match(obj)
end

You can test this method in an irb session:

(irb)
>> number?(7)
=> #<MatchData "7" 1:nil>
>> !!number?(7)
=> true
>> number?(-Math::PI)
=> #<MatchData "-3.141592653589793" 1:".141592653589793">
>> !!number?(-Math::PI)
=> true
>> number?('hello world')
=> nil
>> !!number?('hello world')
=> false

For a detailed explanation of the regex involved here, check out this blog article :)

Line Break in XML formatting?

If you are refering to res strings, use CDATA with \n.

<string name="about">
    <![CDATA[
 Author: Sergio Abreu\n
 http://sites.sitesbr.net
  ]]>        
</string>

Calculate the execution time of a method

StopWatch class looks for your best solution.

Stopwatch sw = Stopwatch.StartNew();
DoSomeWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

Also it has a static field called Stopwatch.IsHighResolution. Of course, this is a hardware and operating system issue.

Indicates whether the timer is based on a high-resolution performance counter.

Tools to get a pictorial function call graph of code

You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.

jQuery UI Accordion Expand/Collapse All

Using an example about for Taifun, I modified to allow expand and collapse.

... // hook up the expand/collapse all

var expandLink = $('.accordion-expand-all');

expandLink.click(function () {

$(".ui-accordion-content").toggle();
});

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

Adding 'serial' to existing column in Postgres

You can also use START WITH to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,

SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');