Programs & Examples On #Returnurl

Is the URL where a user is redirected after being authenticated.

Facebook Callback appends '#_=_' to Return URL

TL;DR

if (window.location.hash === "#_=_"){
    history.replaceState 
        ? history.replaceState(null, null, window.location.href.split("#")[0])
        : window.location.hash = "";
}

Full version with step by step instructions

// Test for the ugliness.
if (window.location.hash === "#_=_"){

    // Check if the browser supports history.replaceState.
    if (history.replaceState) {

        // Keep the exact URL up to the hash.
        var cleanHref = window.location.href.split("#")[0];

        // Replace the URL in the address bar without messing with the back button.
        history.replaceState(null, null, cleanHref);

    } else {

        // Well, you're on an old browser, we can get rid of the _=_ but not the #.
        window.location.hash = "";

    }

}

Step by step:

  1. We'll only get into the code block if the fragment is #_=_.
  2. Check if the browser supports the HTML5 window.replaceState method.
    1. Clean the URL by splitting on # and taking only the first part.
    2. Tell history to replace the current page state with the clean URL. This modifies the current history entry instead of creating a new one. What this means is the back and forward buttons will work just the way you want. ;-)
  3. If the browser does not support the awesome HTML 5 history methods then just clean up the URL as best you can by setting the hash to empty string. This is a poor fallback because it still leaves a trailing hash (example.com/#) and also it adds a history entry, so the back button will take you back to #_-_.

Learn more about history.replaceState.

Learn more about window.location.

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

How to loop through a plain JavaScript object with the objects as members?

Here comes the improved and recursive version of AgileJon's solution (demo):

function loopThrough(obj){
  for(var key in obj){
    // skip loop if the property is from prototype
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      //your code
      console.log(key+" = "+obj[key]);
    } else {
      loopThrough(obj[key]);
    }
  }
}
loopThrough(validation_messages);

This solution works for all kinds of different depths.

How to verify if a file exists in a batch file?

You can use IF EXIST to check for a file:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

If you do not need an "else", you can do something like this:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

Here's a working example of searching for a file or a folder:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

answer for me was to fix a gridview control which contained a template field that had a dropdownlist which was loaded with a monstrous amount of selectable items- i replaced the DDL with a label field whose data is generated from a function. (i was originally going to allow gridview editing, but have switched to allowing edits on a separate panel displaying the DDL for that field for just that record). hope this might help someone.

find index of an int in a list

FindIndex seems to be what you're looking for:

FindIndex(Predicate<T>)

Usage:

list1.FindIndex(x => x==5);

Example:

// given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5);  // should return 3, as list1[3] == 5;

Password hash function for Excel VBA

These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.

Public Function SHA1(ByVal s As String) As String
    Dim Enc As Object, Prov As Object
    Dim Hash() As Byte, i As Integer

    Set Enc = CreateObject("System.Text.UTF8Encoding")
    Set Prov = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")

    Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))

    SHA1 = ""
    For i = LBound(Hash) To UBound(Hash)
        SHA1 = SHA1 & Hex(Hash(i) \ 16) & Hex(Hash(i) Mod 16)
    Next
End Function

How to register ASP.NET 2.0 to web server(IIS7)?

If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.

How to create roles in ASP.NET Core and assign them to users?

The following code will work ISA.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, 
        IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        CreateRolesAndAdminUser(serviceProvider);
    }

    private static void CreateRolesAndAdminUser(IServiceProvider serviceProvider)
    {
        const string adminRoleName = "Administrator";
        string[] roleNames = { adminRoleName, "Manager", "Member" };

        foreach (string roleName in roleNames)
        {
            CreateRole(serviceProvider, roleName);
        }

        // Get these value from "appsettings.json" file.
        string adminUserEmail = "[email protected]";
        string adminPwd = "_AStrongP1@ssword!";
        AddUserToRole(serviceProvider, adminUserEmail, adminPwd, adminRoleName);
    }

    /// <summary>
    /// Create a role if not exists.
    /// </summary>
    /// <param name="serviceProvider">Service Provider</param>
    /// <param name="roleName">Role Name</param>
    private static void CreateRole(IServiceProvider serviceProvider, string roleName)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        Task<bool> roleExists = roleManager.RoleExistsAsync(roleName);
        roleExists.Wait();

        if (!roleExists.Result)
        {
            Task<IdentityResult> roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
            roleResult.Wait();
        }
    }

    /// <summary>
    /// Add user to a role if the user exists, otherwise, create the user and adds him to the role.
    /// </summary>
    /// <param name="serviceProvider">Service Provider</param>
    /// <param name="userEmail">User Email</param>
    /// <param name="userPwd">User Password. Used to create the user if not exists.</param>
    /// <param name="roleName">Role Name</param>
    private static void AddUserToRole(IServiceProvider serviceProvider, string userEmail, 
        string userPwd, string roleName)
    {
        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

        Task<ApplicationUser> checkAppUser = userManager.FindByEmailAsync(userEmail);
        checkAppUser.Wait();

        ApplicationUser appUser = checkAppUser.Result;

        if (checkAppUser.Result == null)
        {
            ApplicationUser newAppUser = new ApplicationUser
            {
                Email = userEmail,
                UserName = userEmail
            };

            Task<IdentityResult> taskCreateAppUser = userManager.CreateAsync(newAppUser, userPwd);
            taskCreateAppUser.Wait();

            if (taskCreateAppUser.Result.Succeeded)
            {
                appUser = newAppUser;
            }
        }

        Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(appUser, roleName);
        newUserRole.Wait();
    }

Python: Find in list

Definition and Usage

the count() method returns the number of elements with the specified value.

Syntax

list.count(value)

example:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Question's example:

item = someSortOfSelection()

if myList.count(item) >= 1 :

    doMySpecialFunction(item)

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

cut or awk command to print first field of first row

You can kill the process which is running the container.

With this command you can list the processes related with the docker container:

ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')

Now you have the process ids to kill with kill or kill -9.

"installation of package 'FILE_PATH' had non-zero exit status" in R

I had the same problem, but the answer from @little_chemist helped me sorting it out. When installing packages from a file in a unix OS (Ubuntu 18.04 for me), the file can not be zipped. You are using:

install.packages("/home/p/Research/14_bivpois-Rcode.zip", repos = NULL, type="source")

I noticed the solution was as simple as unzipping the package. Additionally, unzip all (installation related?) packages inside, as @little_chemist points out. Then use install.packages:

install.packages("/home/p/Research/14_bivpois-Rcode", repos = NULL, type="source")

Hope it helps!

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

How to get complete current url for Cakephp

for CakePHP 3:

$this->Url->build(null, true) // full URL with hostname

$this->Url->build(null) // /controller/action/params

Global Events in Angular

DO Not Use EventEmitter for your service communication.

You should use one of the Observable types. I personally like BehaviorSubject.

Simple example:

You can pass initial state, here I passing null

let subject = new BehaviorSubject(null);

When you want to update the subject

subject.next(myObject)

Observe from any service or component and act when it gets new updates.

subject.subscribe(this.YOURMETHOD);

Here is more information..

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you are using Jersey 2.x use following dependency:

<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.XX</version>
</dependency>  

Where XX could be any particular version you look for. Jersey Containers.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

What is the difference between functional and non-functional requirements?

Functional requirements are those which are related to the technical functionality of the system.

non-functional requirement is a requirement that specifies criteria that can be used to judge the operation of a system in particular conditions, rather than specific behaviors.

For example if you consider a shopping site, adding items to cart, browsing different items, applying offers and deals and successfully placing orders comes under functional requirements.

Where as performance of the system in peak hours, time taken for the system to retrieve data from DB, security of the user data, ability of the system to handle if large number of users login comes under non functional requirements.

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Easiest way on Safari 11.0 macOS SIERRA 10.12.6: Reload Page From Origin, you can use help to find out where in the menu it is located, or you can use the shortcut option(alt) + command + R.

Why are static variables considered evil?

Suppose that if you have an application with many users and you have defined a static function that saves state within a static variable, then every user will modify the state of other users.

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

The absolute easiest way to stream a file into browser using ASP.NET MVC is this:

public ActionResult DownloadFile() {
    return File(@"c:\path\to\somefile.pdf", "application/pdf", "Your Filename.pdf");
}

This is easier than the method suggested by @azarc3 since you don't even need to read the bytes.

Credit goes to: http://prideparrot.com/blog/archive/2012/8/uploading_and_returning_files#how_to_return_a_file_as_response

** Edit **

Apparently my 'answer' is the same as the OP's question. But I am not facing the problem he is having. Probably this was an issue with older version of ASP.NET MVC?

jQuery - hashchange event

Use Modernizr for detection of feature capabilities. In general jQuery offers to detect browser features: http://api.jquery.com/jQuery.support/. However, hashchange is not on the list.

The wiki of Modernizr offers a list of libraries to add HTML5 capabilities to old browsers. The list for hashchange includes a pointer to the project HTML5 History API, which seems to offer the functionality you would need if you wanted to emulate the behavior in old browsers.

UIWebView open links in Safari

One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.

What you can do to prevent this (thanks Wade) is:

if (inType == UIWebViewNavigationTypeLinkClicked) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;

You might also want to handle the UIWebViewNavigationTypeFormSubmitted and UIWebViewNavigationTypeFormResubmitted types.

How do I use a Boolean in Python?

Unlike Java where you would declare boolean flag = True, in Python you can just declare myFlag = True

Python would interpret this as a boolean variable

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to send an email with Gmail as provider using Python?

Seems like problem of the old smtplib. In python2.7 everything works fine.

Update: Yep, server.ehlo() also could help.

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

MAMP mysql server won't start. No mysql processes are running

  1. Stop MAMP server.
  2. Then go in following folder:

Applications/MAMP/db/mysql56/

In this folder, please remove all direct files except folders. This means that you have to remove only auto.cnf, ibdata, ib_logfile, not any folders.

  1. Restart MAMP server.

It should work.

Thank you.

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

What is the best way to concatenate two vectors?

All the solutions are correct, but I found it easier just write a function to implement this. like this:

template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
    t1->insert(t1->end(), t2->begin(), t2->end());
}

That way you can avoid the temporary placement like this:

ContainerInsert(vec, GetSomeVector());

Embed a PowerPoint presentation into HTML

I spent a while looking into this and pretty much all of the freeware and shareware on the web sucked. This included software to directly convert the .ppt file to Flash or some sort of video format and also software to record your desktop screen. Software was clunky, and the quality was poor.

The solution we eventually came up with is a little bit manual, but it gave by far the best quality results:

  1. Export the .ppt file into some sort of image format (.bmp, .jpeg, .png, .tif) - it writes out one file per slide
  2. Import all the slide image files into Google Picasa and use them to create a video. You can add in some nice simple transitions (it hasn't got some of the horrific .ppt one's, but who cares) and it dumps out a WMV file of your specified resolution.

Saving out as .wmv isn't perfect, but I'm sure it's probably quite straightforward to convert that to some other format or Flash. We were looking to get them up on YouTube and this did the trick.

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

Build query string for System.Net.HttpClient get

Since I have to reuse this few time, I came up with this class that simply help to abstract how the query string is composed.

public class UriBuilderExt
{
    private NameValueCollection collection;
    private UriBuilder builder;

    public UriBuilderExt(string uri)
    {
        builder = new UriBuilder(uri);
        collection = System.Web.HttpUtility.ParseQueryString(string.Empty);
    }

    public void AddParameter(string key, string value) {
        collection.Add(key, value);
    }

    public Uri Uri{
        get
        {
            builder.Query = collection.ToString();
            return builder.Uri;
        }
    }

}

The use will be simplify to something like this:

var builder = new UriBuilderExt("http://example.com/");
builder.AddParameter("foo", "bar<>&-baz");
builder.AddParameter("bar", "second");
var uri = builder.Uri;

that will return the uri: http://example.com/?foo=bar%3c%3e%26-baz&bar=second

Row count where data exists

I found this method on http://www.mrexcel.com/

This computes the number of non-blank cells in column A of worksheet named "Data"

With Worksheets("Data")
  Ndt =Application.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
  debug.print Ndt
End With

The result is printed to the immediate window. You need to subtract 1 (or more) if column A has a header line (or lines) you do not wish to count.

Remove directory from remote repository after adding them to .gitignore

The rules in your .gitignore file only apply to untracked files. Since the files under that directory were already committed in your repository, you have to unstage them, create a commit, and push that to GitHub:

git rm -r --cached some-directory
git commit -m 'Remove the now ignored directory "some-directory"'
git push origin master

You can't delete the file from your history without rewriting the history of your repository - you shouldn't do this if anyone else is working with your repository, or you're using it from multiple computers. If you still want to do that, you can use git filter-branch to rewrite the history - there is a helpful guide to that here.

Additionally, note the output from git rm -r --cached some-directory will be something like:

rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg'
rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg'
rm 'some-directory/.htaccess'
rm 'some-directory/logo.jpg'

The rm is feedback from git about the repository; the files are still in the working directory.

Unique on a dataframe with only selected columns

Using unique():

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])),]

Build Maven Project Without Running Unit Tests

Run following command:

mvn clean install -DskipTests=true

Java generating Strings with placeholders

If you can change the format of your placeholder, you could use String.format(). If not, you could also replace it as pre-processing.

String.format("hello %s!", "world");

More information in this other thread.

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Both are effectively the same class (you can look at the disassembly). HashTable was created first before .Net had generics. Dictionary, however is a generic class and gives you strong typing benefits. I would never use HashTable since Dictionary costs you nothing to use.

sudo: port: command not found

You could try to source your profile file to update your environment:

$ source ~/.profile

Running Tensorflow in Jupyter Notebook

  1. install tensorflow by running these commands in anoconda shell or in console:

    conda create -n tensorflow python=3.5
    activate tensorflow
    conda install pandas matplotlib jupyter notebook scipy scikit-learn
    pip install tensorflow
    
  2. close the console and reopen it and type these commands:

    activate tensorflow 
    jupyter notebook 
    

Can I position an element fixed relative to parent?

Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.


To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element.

For example:

#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }

This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.


To position an element "fixed" relative to the window, you want position:fixed, and can use top:, left:, right:, and bottom: to position as you see fit.

For example:

#yourDiv { position:fixed; bottom:40px; right:40px; }

This will position yourDiv fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.

error: expected class-name before ‘{’ token

This should be a comment, but comments don't allow multi-line code.

Here's what's happening:

in Event.cpp

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

it isn't defined yet, so keep going

#define EVENT_H_
#include "common.h"

common.h gets processed ok

#include "Item.h"

Item.h gets processed ok

#include "Flight.h"

Flight.h gets processed ok

#include "Landing.h"

preprocessor starts processing Landing.h

#ifndef LANDING_H_

not defined yet, keep going

#define LANDING_H_

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

This IS defined already, the whole rest of the file gets skipped. Continuing with Landing.h

class Landing: public Event {

The preprocessor doesn't care about this, but the compiler goes "WTH is Event? I haven't heard about Event yet."

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

SIMPLE SOLUTION

  1. Create a new blank project and save it
  2. using NOTEPAD open the .VBP of the new project and copy the MSCOMCTL line
  3. using NOTEPAD open the .VBP file of your project
  4. replace the MSCOMCTL line and save it

DONE

good luck

X-Frame-Options Allow-From multiple domains

From RFC 7034:

Wildcards or lists to declare multiple domains in one ALLOW-FROM statement are not permitted

So,

How do I set the X-Frame-Options: ALLOW-FROM to support more than a single domain?

You can't. As a workaround you can use different URLs for different partners. For each URL you can use it's own X-Frame-Options value. For example:

partner   iframe URL       ALLOW-FROM
---------------------------------------
Facebook  fb.yoursite.com  facebook.com
VK.COM    vk.yoursite.com  vk.com

For yousite.com you can just use X-Frame-Options: deny.

BTW, for now Chrome (and all webkit-based browsers) does not support ALLOW-FROM statements at all.

TypeError: Missing 1 required positional argument: 'self'

You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

So, simply call Pump.getPumps() .

In java, it is termed as static method.

How to create a Restful web service with input parameters?

If you want query parameters, you use @QueryParam.

public Todo getXML(@QueryParam("summary") String x, 
                   @QueryParam("description") String y)

But you won't be able to send a PUT from a plain web browser (today). If you type in the URL directly, it will be a GET.

Philosophically, this looks like it should be a POST, though. In REST, you typically either POST to a common resource, /todo, where that resource creates and returns a new resource, or you PUT to a specifically-identified resource, like /todo/<id>, for creation and/or update.

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

How can I print each command before executing?

set -x is fine, but if you do something like:

set -x;
command;
set +x;

it would result in printing

+ command
+ set +x;

You can use a subshell to prevent that such as:

(set -x; command)

which would just print the command.

jQuery: How to capture the TAB keypress within a Textbox

Try this:

$('#contra').focusout(function (){
    $('#btnPassword').focus();
});

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

Grab a segment of an array in Java without creating a new array on heap

I see the subList answer is already here, but here's code that demonstrates that it's a true sublist, not a copy:

public class SubListTest extends TestCase {
    public void testSubarray() throws Exception {
        Integer[] array = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(array);
        List<Integer> subList = list.subList(2, 4);
        assertEquals(2, subList.size());
        assertEquals((Integer) 3, subList.get(0));
        list.set(2, 7);
        assertEquals((Integer) 7, subList.get(0));
    }
}

I don't believe there's a good way to do this directly with arrays, however.

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

Serialize and Deserialize Json and Json Array in Unity

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

iCheck check if checkbox is checked

this works for me... try it

_x000D_
_x000D_
// Check #x_x000D_
$( "#x" ).prop( "checked", true );_x000D_
 _x000D_
// Uncheck #x_x000D_
$( "#x" ).prop( "checked", false );
_x000D_
_x000D_
_x000D_

Failed to resolve: com.android.support:appcompat-v7:28.0

Ensure that your buildToolsVersion version tallies with your app compact version.

In order to find both installed compileSdkVersion and buildToolsVersion go to Tools > SDK Manager. This will pull up a window that will allow you to manage your compileSdkVersion and your buildToolsVersion.

To see the exact version breakdowns ensure you have the Show Package Details checkbox checked.

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3" (HERE)
    defaultConfig {
        applicationId "com.example.truecitizenquiz"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0' (HERE)
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

OS X Terminal Colors

If you want to have your ls colorized you have to edit your ~/.bash_profile file and add the following line (if not already written) :

source .bashrc

Then you edit or create ~/.bashrc file and write an alias to the ls command :

alias ls="ls -G"

Now you have to type source .bashrc in a terminal if already launched, or simply open a new terminal.

If you want more options in your ls juste read the manual ( man ls ). Options are not exactly the same as in a GNU/Linux system.

Finding repeated words on a string and counting the repetitions

import java.util.HashMap;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String inpStr = in.nextLine();
    int key;

    HashMap<String,Integer> hm = new HashMap<String,Integer>();
    String[] strArr = inpStr.split(" ");

    for(int i=0;i<strArr.length;i++){
        if(hm.containsKey(strArr[i])){
            key = hm.get(strArr[i]);
            hm.put(strArr[i],key+1);

        }
        else{
            hm.put(strArr[i],1);
        }   
    }
    System.out.println(hm);
}

}

Builder Pattern in Effective Java

This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.

NutritionalFacts n = new NutritionalFacts()

Builder b = new n.Builder(10).carbo(23).fat(1).build();

Nested Classes

Serializing with Jackson (JSON) - getting "No serializer found"?

As already described, the default configuration of an ObjectMapper instance is to only access properties that are public fields or have public getters/setters. An alternative to changing the class definition to make a field public or to provide a public getter/setter is to specify (to the underlying VisibilityChecker) a different property visibility rule. Jackson 1.9 provides the ObjectMapper.setVisibility() convenience method for doing so. For the example in the original question, I'd likely configure this as

myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

For Jackson >2.0:

myObjectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

For more information and details on related configuration options, I recommend reviewing the JavaDocs on ObjectMapper.setVisibility().

Change Orientation of Bluestack : portrait/landscape mode

New version 4.100.x.xxxx

Try this:

More Apps > Android Settings > Accessibility > Auto-rotate screen = Enabled

enter image description here

How to download a file from a website in C#

You can use this code to Download file from a WebSite to Desktop:

using System.Net;

WebClient client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");

Get the Id of current table row with Jquery

$('input[type=button]' ).click(function() {
   var bid = jQuery(this).attr('id'); // button ID 
   var trid = $(this).parents('tr:first').attr('id'); // table row ID 
 });

wait() or sleep() function in jquery?

delay() will not do the job. The problem with delay() is it's part of the animation system, and only applies to animation queues.

What if you want to wait before executing something outside of animation??

Use this:

window.setTimeout(function(){
                 // do whatever you want to do     
                  }, 600);

What happens?: In this scenario it waits 600 miliseconds before executing the code specified within the curly braces.

This helped me a great deal once I figured it out and hope it will help you as well!

IMPORTANT NOTICE: 'window.setTimeout' happens asynchronously. Keep that in mind when writing your code!

Is putting a div inside an anchor ever correct?

you can achieve this by adding "::before" Pseudo-element

Pure CSS Trick ;)

_x000D_
_x000D_
a:before{_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  z-index: 1;_x000D_
  pointer-events: auto;_x000D_
  content: "";_x000D_
  background-color: rgba(0,0,0,0);_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="card" style="width: 18rem;">_x000D_
  <img src="https://via.placeholder.com/250" class="card-img-top" alt="...">_x000D_
  <div class="card-body">_x000D_
    <h5 class="card-title">Card with stretched link</h5>_x000D_
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>_x000D_
    <a href="#" class="btn btn-primary stretched-link">Go somewhere</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

Displaying one div on top of another

Have the style for the parent div and the child divs' set as following. It worked for my case, hope it helps you as well..

<div id="parentDiv">
  <div id="backdrop"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

in your JS:

document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any

or in your CSS as in this working example:::

_x000D_
_x000D_
#parentDiv{_x000D_
  background: yellow;_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  position: relative;_x000D_
}_x000D_
#backdrop{_x000D_
  background: red;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  position: absolute;_x000D_
}_x000D_
#curtain{_x000D_
  background: green;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  position: absolute;_x000D_
  z-index: 2;_x000D_
  margin: 100px 0px 150px 100px;_x000D_
}
_x000D_
<div id="parentDiv"><h2>_x000D_
  THIS IS PARENT DIV_x000D_
  </h2>_x000D_
  <div id="backdrop"><h4>_x000D_
  THIS IS BACKDROP DIV_x000D_
  </h4></div>_x000D_
  <div id="curtain"><h6>_x000D_
  THIS IS CURTAIN DIV_x000D_
  </h6></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Site does not exist error for a2ensite

I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.

Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.

Before read this question I did not have a clue what was going on with the server.

Pretty nice solution.

Just summarizing I did the following steps on Terminal:

1) Access sites-enabled folder

$ cd /etc/apache2/sites-enabled

2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published

$ sudo rm <my-old-website-without-.conf>

3) Rename the website vhost files changing its extension adding .conf to the end

$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf

4) Republish the new and correct vhost file

$ sudo a2ensite mywebsite.conf

5) Check the website on browser and have fun! :)

Eloquent Collection: Counting and Detect Empty

There are several methods given in Laravel for checking results count/check empty/not empty:

$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.

Count textarea characters

    $(document).ready(function(){ 
    $('#characterLeft').text('140 characters left');
    $('#message').keydown(function () {
        var max = 140;
        var len = $(this).val().length;
        if (len >= max) {
            $('#characterLeft').text('You have reached the limit');
            $('#characterLeft').addClass('red');
            $('#btnSubmit').addClass('disabled');            
        } 
        else {
            var ch = max - len;
            $('#characterLeft').text(ch + ' characters left');
            $('#btnSubmit').removeClass('disabled');
            $('#characterLeft').removeClass('red');            
        }
    });    
});

Split a String into an array in Swift?

Or without closures you can do just this in Swift 2:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

Why is a ConcurrentModificationException thrown and how to debug it

In Java 8, you can use lambda expression:

map.keySet().removeIf(key -> key condition);

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Most of the time its happen with not insert proper valid OAuth redirect URL in the product section of the FB dashboard.I suggest follow my bellow steps

01.Check the basic setting of the app is okay with bellow picture with you

enter image description here

02.check whether you have add a product

If not you can easily add log in product by clicking + sine as I show in the bellow.

If Yes just got to inside of the product setting. enter image description here

03.The check whether you have provide valid OAuth redirect URL

Its simple mean what should after login.It is not other than that your call back URl.You can see in my bellow picture I have added several redirect URLs. enter image description here

  1. have any problem further Watch my video-- > https://www.youtube.com/watch?v=mdhubrzV5y8&t=3s

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

How can I execute Shell script in Jenkinsfile?

Based on the number of views this question has, it looks like a lot of people are visiting this to see how to set up a job that executes a shell script.

These are the steps to execute a shell script in Jenkins:

  • In the main page of Jenkins select New Item.
  • Enter an item name like "my shell script job" and chose Freestyle project. Press OK.
  • On the configuration page, in the Build block click in the Add build step dropdown and select Execute shell.
  • In the textarea you can either paste a script or indicate how to run an existing script. So you can either say:

    #!/bin/bash
    
    echo "hello, today is $(date)" > /tmp/jenkins_test
    

    or just

    /path/to/your/script.sh
    
  • Click Save.

Now the newly created job should appear in the main page of Jenkins, together with the other ones. Open it and select Build now to see if it works. Once it has finished pick that specific build from the build history and read the Console output to see if everything happened as desired.

You can get more details in the document Create a Jenkins shell script job in GitHub.

Get push notification while App in foreground iOS

Here is the code to receive Push Notification when app in active state (foreground or open). UNUserNotificationCenter documentation

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}

If you need to access userInfo of notification use code: notification.request.content.userInfo

Convert string (without any separator) to list

Instead of converting to a list, you could just iterate over the first string and create a second string by adding each of the digit characters you find to that new string.

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

How to explicitly obtain post data in Spring MVC?

Another answer to the OP's exact question is to set the consumes content type to "text/plain" and then declare a @RequestBody String input parameter. This will pass the text of the POST data in as the declared String variable (postPayload in the following example).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
    public ModelAndView someMethod(@RequestBody String postPayload) {    
        // ...    
    }

Force decimal point instead of comma in HTML5 number input (client-side)

According to the spec, You can use any as the value of step attribute:

<input type="number" step="any">

How can I convert an RGB image into grayscale in Python?

image=myCamera.getImage().crop(xx,xx,xx,xx).scale(xx,xx).greyscale()

You can use greyscale() directly for the transformation.

Launch Image does not show up in my iOS App

For some reason, I had to change the asset catalog location to "relative to project" for this to work.

I had also deleted the app from my phone and reinstalled, but it was probably the "relative to project" that did it.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I solved it by deleting "/.idea/libraries" from project. Thanks

Click through div to underlying elements

I couldn't always use pointer-events: none in my scenario, because I wanted both the overlay and the underlying element(s) to be clickable / selectable.

The DOM structure looked like this:

<div id="outerElement">
   <div id="canvas-wrapper">
      <canvas id="overlay"></canvas>
   </div>
   <!-- Omitted: element(s) behind canvas that should still be selectable -->
</div>

(The outerElement, canvas-wrapper and canvas elements have the same size.)

To make the elements behind the canvas act normally (e.g. selectable, editable), I used the following code:

canvasWrapper.style.pointerEvents = 'none';

outerElement.addEventListener('mousedown', event => {
    const clickedOnElementInCanvas = yourCheck // TODO: check if the event *would* click a canvas element.
    if (!clickedOnElementInCanvas) {

        // if necessary, add logic to deselect your canvas elements ...

        wrapper.style.pointerEvents = 'none';
        return true;
    }

    // Check if we emitted the event ourselves (avoid endless loop)
    if (event.isTrusted) {
        // Manually forward element to the canvas
        const mouseEvent = new MouseEvent(event.type, event);
        canvas.dispatchEvent(mouseEvent);
        mouseEvent.stopPropagation();
    }
    return true;
});

Some canvas objects also came with input fields, so I had to allow keyboard events, too. To do this, I had to update the pointerEvents property based on whether a canvas input field was currently focused or not:

onCanvasModified(canvas, () => {
    const inputFieldInCanvasActive = // TODO: Check if an input field of the canvas is active.
    wrapper.style.pointerEvents = inputFieldInCanvasActive  ? 'auto' : 'none';
});

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

Bootstrap 4: responsive sidebar menu to top navbar

It could be done in Bootstrap 4 using the responsive grid columns. One column for the sidebar and one for the main content.

Bootstrap 4 Sidebar switch to Top Navbar on mobile

<div class="container-fluid h-100">
    <div class="row h-100">
        <aside class="col-12 col-md-2 p-0 bg-dark">
            <nav class="navbar navbar-expand navbar-dark bg-dark flex-md-column flex-row align-items-start">
                <div class="collapse navbar-collapse">
                    <ul class="flex-md-column flex-row navbar-nav w-100 justify-content-between">
                        <li class="nav-item">
                            <a class="nav-link pl-0" href="#">Link</a>
                        </li>
                        ..
                    </ul>
                </div>
            </nav>
        </aside>
        <main class="col">
            ..
        </main>
    </div>
</div>

Alternate sidebar to top
Fixed sidebar to top

For the reverse (Top Navbar that becomes a Sidebar), can be done like this example

Request format is unrecognized for URL unexpectedly ending in

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

sed command with -i option failing on Mac, but works on Linux

Your Mac does indeed run a BASH shell, but this is more a question of which implementation of sed you are dealing with. On a Mac sed comes from BSD and is subtly different from the sed you might find on a typical Linux box. I suggest you man sed.

How to change the server port from 3000?

You can change it in the webpack.dev.js file in config folder.

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

How to add a char/int to an char array in C?

In C/C++ a string is an array of char terminated with a NULL byte ('\0');

  1. Your string str has not been initialized.
  2. You must concatenate strings and you are trying to concatenate a single char (without the null byte so it's not a string) to a string.

The code should look like this:

char str[1024] = "Hello World"; //this will add all characters and a NULL byte to the array
char tmp[2] = "."; //this is a string with the dot 
strcat(str, tmp);  //here you concatenate the two strings

Note that you can assign a string literal to an array only during its declaration.
For example the following code is not permitted:

char str[1024];
str = "Hello World"; //FORBIDDEN

and should be replaced with

char str[1024];
strcpy(str, "Hello World"); //here you copy "Hello World" inside the src array 

How can I uninstall an application using PowerShell?

Here is the PowerShell script using msiexec:

echo "Getting product code"
$ProductCode = Get-WmiObject win32_product -Filter "Name='Name of my Software in Add Remove Program Window'" | Select-Object -Expand IdentifyingNumber
echo "removing Product"
# Out-Null argument is just for keeping the power shell command window waiting for msiexec command to finish else it moves to execute the next echo command
& msiexec /x $ProductCode | Out-Null
echo "uninstallation finished"

jQuery set radio button

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

How do I show/hide a UIBarButtonItem?

There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

how to parse xml to java object?

For performing Unmarshall using JAXB:

1) Convert given XML to XSD(by yourself or by online convertor),

2) Create a JAXB project in eclipse,

3) Create XSD file and paste that converted XSD content in it,

4) Right click on **XSD file--> Generate--> JAXB Classes-->follow the instructions(this will create all nessasary .java files in src, i.e., one package-info, object factory and pojo class),

5) Create another .java file in src to operate unmarshall operation, and run it.

Happy Coding !!

Select Multiple Fields from List in Linq

Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:

var cats = listObject
    .Select(i => new { i.category_id, i.category_name })
    .Distinct()
    .OrderByDescending(i => i.category_name)
    .ToArray();

Since you (apparently) need to store it for later use, you could use the GroupBy operator:

Data[] cats = listObject
    .GroupBy(i => new { i.category_id, i.category_name })
    .OrderByDescending(g => g.Key.category_name)
    .Select(g => g.First())
    .ToArray();

Chart.js canvas resize

If anyone is having problems, I found a solution that doesn't involve sacrificing responsiveness etc.

Simply wrap your canvas in a div container (no styling) and reset the contents of the div to an empty canvas with ID before calling the Chart constructor.

Example:

HTML:

<div id="chartContainer">
    <canvas id="myChart"></canvas>
</div>

JS:

$("#chartContainer").html('<canvas id="myChart"></canvas>');
//call new Chart() as usual

Failing to run jar file from command line: “no main manifest attribute”

You need to include "Main class" attribute in Manisfest.mf file in Jar

For example: Main-Class: MyClassName

Second thing, To add Manifest file in Your jar, You can manually create file in your workspace folder, and refresh in Eclipse Project explorer.

While exporting, Eclipse will create a Jar which will include your manifest.

Cheers !!

Hide Show content-list with only CSS, no javascript used

I know it's an old post but what about this solution (I've made a JSFiddle to illustrate it)... Solution that uses the :after pseudo elements of <span> to show/hide the <span> switch link itself (in addition to the .alert message it must show/hide). When the pseudo element loses it's focus, the message is hidden.

The initial situation is a hidden message that appears when the <span> with the :after content : "Show Me"; is focused. When this <span> is focused, it's :after content becomes empty while the :after content of the second <span> (that was initially empty) turns to "Hide Me". So, when you click this second <span> the first one loses it's focus and the situation comes back to it's initial state.

I started on the solution offered by @Vector I kept the DOM'situation presented ky @Frederic Kizar

HTML:

<span class="span3" tabindex="0"></span>
<span class="span2" tabindex="0"></span>
<p class="alert" >Some message to show here</p>

CSS:

body {
    display: inline-block;
}
.span3 ~ .span2:after{
    content:"";
}
.span3:focus ~ .alert  {
    display:block;
}
.span3:focus ~ .span2:after  {
    content:"Hide Me";
}
.span3:after  {
    content: "Show Me";
}
.span3:focus:after  {
    content: "";
}
.alert  {
    display:none;
}

How can I make a "color map" plot in matlab?

gevang's answer is great. There's another way as well to do this directly by using pcolor. Code:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z); 
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;

Output:

enter image description here

Also, pcolor is flat too, as show here (pcolor is the 2d base; the 3d figure above it is generated using mesh):

enter image description here

What's the best way to store a group of constants that my program uses?

I would suggest static class with static readonly. Please find the code snippet below:

  public static class CachedKeysManager
    {
        public static readonly string DistributorList = "distributorList";
    }

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

Where is Python language used?

Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.

Postgres ERROR: could not open file for reading: Permission denied

Copy the CSV file to /tmp

For me this solved the issue.

Creating an Arraylist of Objects

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

ASP.NET Core Identity - get current user

private readonly UserManager<AppUser> _userManager;

 public AccountsController(UserManager<AppUser> userManager)
 {
            _userManager = userManager;
 }

[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
   var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
   var user = await _userManager.FindByIdAsync(userId);

   ProfileUpdateModel model = new ProfileUpdateModel();
   model.Email = user.Email;
   model.FirstName = user.FirstName;
   model.LastName = user.LastName;
   model.PhoneNumber = user.PhoneNumber;

   return new OkObjectResult(model);
}

How do I prevent mails sent through PHP mail() from going to spam?

$fromMail = 'set your from mail';
$boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
$subjectMail = "New design submitted by " . $userDisplayName;


$contentHtml = '<div>Dear Admin<br /><br />The following design is submitted by '. $userName .'.<br /><br /><a href="'.$sdLink.'"><b>Click here</b></a> to check the design.</div>';
$contentHtml .= '<div><a href="'.$imageUrl.'"><img src="'.$imageUrl.'" width="250" height="95" border="0" alt="my picture"></a></div>';
$contentHtml .= '<div>Name : '.$name.'<br />Description : '. $description .'</div>';

$headersMail = '';
$headersMail .= 'From: ' . $fromMail . "\r\n" . 'Reply-To: ' . $fromMail . "\r\n";
$headersMail .= 'Return-Path: ' . $fromMail . "\r\n";
$headersMail .= 'MIME-Version: 1.0' . "\r\n";
$headersMail .= "Content-Type: multipart/alternative; boundary = \"" . $boundary . "\"\r\n\r\n";
$headersMail .= '--' . $boundary . "\r\n";
$headersMail .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
$headersMail .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$headersMail .= rtrim(chunk_split(base64_encode($contentHtml)));

try {
    if (mail($toMail, $subjectMail, "", $headersMail)) {
        $status = 'success';
        $msg = 'Mail sent successfully.';
    } else {
        $status = 'failed';
        $msg = 'Unable to send mail.';
    }
} catch(Exception $e) {
    $msg = $e->getMessage();
}

This works fine for me.It includes mail with image and a link and works for all sorts of mail ids. The clue is to use all the header perfectly.

If you are testing it from localhost, then set the below before checking:

How to set mail send from localhost xampp:

  1. comment everything in D:/xampp/sendmail/sendmail.ini and mention the below under

    [sendmail]

    smtp_server=smtp.gmail.com smtp_port=587 error_logfile=error.log debug_logfile=debug.log [email protected] auth_password=your-mail-password [email protected]

  2. In D:/xampp/php/php.ini a. Under

    [mail function]

    SMTP = smtp.gmail.com smtp_port = 587

b. set sendmail_from = [email protected] c. uncomment sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t" Hence it should be look like below

sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t"

d. comment sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe" Hence it should be look like below

;sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe"

e. mail.add_x_header=Off

how to remove time from datetime

just use, (in TSQL)

SELECT convert(varchar, columnName, 101)

in MySQL

SELECT DATE_FORMAT(columnName, '%m/%d/%Y')

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

Predicate in Java

You can view the java doc examples or the example of usage of Predicate here

Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:

 // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    resultset.beforeFirst();
    resultset.setFilter(filter);

Skip first entry in for loop in python?

for item in do_not_use_list_as_a_name[1:-1]:
    #...do whatever

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

keyword not supported data source

I was getting the same error, then updated my connection string as below,

<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Try this it will solve your issue.

How to make Python script run as service?

My non pythonic approach would be using & suffix. That is:

python flashpolicyd.py &

To stop the script

killall flashpolicyd.py

also piping & suffix with disown would put the process under superparent (upper):

python flashpolicyd.pi & disown

How to resolve "must be an instance of string, string given" prior to PHP 7?

Prior to PHP 7 type hinting can only be used to force the types of objects and arrays. Scalar types are not type-hintable. In this case an object of the class string is expected, but you're giving it a (scalar) string. The error message may be funny, but it's not supposed to work to begin with. Given the dynamic typing system, this actually makes some sort of perverted sense.

You can only manually "type hint" scalar types:

function foo($string) {
    if (!is_string($string)) {
        trigger_error('No, you fool!');
        return;
    }
    ...
}

PHP: How to check if image file exists?

public static function is_file_url_exists($url) {
        if (@file_get_contents($url, 0, NULL, 0, 1)) {
            return 1;
        }

        return 0;           
    }

Linux command to print directory structure in the form of a tree

You can use this one:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:

   .
   |-apache2
   |---mod_cache_disk
   |-apparmor
   |-apt
   |---archives
   |-----partial
   |-apt-xapian-index
   |---index.1
   |-dbconfig-common
   |---backups
   |-debconf

Source

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

Disable pasting text into HTML form

You can disable the copy paste option with jQuery by the below script:

jQuery("input").attr("onpaste","return false;");

of by using the bellow oppaste attribute into the input fields.

onpaste="return false;"

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Remove all newlines from inside a string

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

What is DOM element?

See that your statements refer to "elements of the DOM", which are things such as the HTML tags (A, INPUT, etc). Thse statements simply mean that multiple CSS classes may be assigned to one such element.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JAVA HOME is used for setting up the environment variable for JAVA. It means that you are providing a path for compiling a JAVA program and also running the same. So, if you do not set the JAVA HOME( PATH ) and try to run a java or any dependent program in the command prompt.

You will deal with an error as javac : not recognized as internal or external command. Now to set this, Just open your Java jdk then open bin folder then copy the PATH of that bin folder.

Now, go to My computer right click on it----> select properties-----> select Advanced system settings----->Click on Environment Variables------>select New----->give a name in the text box Variable Name and then paste the path in Value.

That's All!!

How print out the contents of a HashMap<String, String> in ascending order based on its values?

you just need to use:

 Map<>.toString().replace("]","\n");

and replaces the ending square bracket of each key=value set with a new line.

How do I remove an object from an array with JavaScript?

Well splice works:

var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []

Do NOT use the delete operator on Arrays. delete will not remove an entry from an Array, it will simply replace it with undefined.

var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]

But maybe you want something like this?

var removeByAttr = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i] 
           && arr[i].hasOwnProperty(attr) 
           && (arguments.length > 2 && arr[i][attr] === value ) ){ 

           arr.splice(i,1);

       }
    }
    return arr;
}

Just an example below.

var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);   
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]

removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]

Android Studio Emulator and "Process finished with exit code 0"

I had this problem and it took me nearly 2 days to resolve...

I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.

Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.

What does the "+" (plus sign) CSS selector mean?

p+p{
//styling the code
}

p+p{
} simply mean find all the adjacent/sibling paragraphs with respect to first paragraph in DOM body.

    <div>
    <input type="text" placeholder="something">
    <p>This is first paragraph</p>
    <button>Button </button>
    <p> This is second paragraph</p>
    <p>This is third paragraph</p>
    </div>

    Styling part 
    <style type="text/css">
        p+p{
            color: red;
            font-weight: bolder;
        }
    </style>

   It will style all sibling paragraph with red color.

final output look like this

enter image description here

Hide header in stack navigator React navigation

You can hide header like this:

<Stack.Screen name="Login" component={Login} options={{headerShown: false}}  />

Using .htaccess to make all .html pages to run as .php files?

Create a .htaccess file at the root of your website and add this line:

[Apache2 @ Ubuntu/Debian: use this directive]

AddType application/x-httpd-php .html .htm

Or, from comment below:

AddType application/x-httpd-php5 .html .htm

If your are running PHP as CGI (probably not the case), you should write instead:

AddHandler application/x-httpd-php .html .htm 

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

JavaFX Application Icon

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png")));

If your icon.png is in resources dir and remember to put a '/' before otherwise it will not work

How to use JavaScript with Selenium WebDriver Java

I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here. How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.

    driver.executeScript("function(arguments[0]);","parameter to send in");

On - window.location.hash - Change?

You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

The code will look like this:

window.location.watch(
    'hash',
    function(id,oldVal,newVal){
        console.log("the window's hash value has changed from "+oldval+" to "+newVal);
    }
);

Then you can test it:

var myHashLink = "home";
window.location = window.location + "#" + myHashLink;

And of course that will trigger your observer function.

How do I parse JSON from a Java HTTPResponse?

Two things which can be done more efficiently:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

If the JSON is actually a single line, then you can also remove the loop and builder.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

Getting JavaScript object key list

obj = {'a':'c','b':'d'}

You can try:

[index for (index in obj)] 

this will return:

['a','b']

to get the list of keys or

[obj[index] for (index in obj)]

to get the values

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}

How can I fill out a Python string with spaces?

you can also center your string:

'{0: ^20}'.format('nice')

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

Maybe try simply

@(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)

also you can use many type of string format like .ToString("dd MMM, yyyy") .ToString("d") etc

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

Which is faster: multiple single INSERTs or one multiple-row INSERT?

You might want to :

  • Check that auto-commit is off
  • Open Connection
  • Send multiple batches of inserts in a single transaction (size of about 4000-10000 rows ? you see)
  • Close connection

Depending on how well your server scales (its definitively ok with PostgreSQl, Oracle and MSSQL), do the thing above with multiple threads and multiple connections.

How do you clone a Git repository into a specific folder?

There is a very easy option using Visual Studio Code:

  1. Install the GitLab workflow extension
  2. Hit Ctrl + Shift + P
  3. Enter the repository URL (that you copied from GitLab, GitHub, etc.)
  4. Choose local repository location on your computer

Nesting CSS classes

No.

You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.

See also my article on CSS inheritance.

Accessing localhost (xampp) from another computer over LAN network - how to?

If someone is still finding it hard, this simple thing worked for me:

  1. On you main system let's say Hosting PC... Go to Control Panel > Windows Defender Firewall > Allow an app or feature through Windows Defender Firewall > Change settings > Find "Apache HTTP Server" > Check both the check-boxes (under Private & Public). See Screenshot

    • In my case there were two "Apache HTTP Server" entries, so I checked both the check-boxes for both entries.
  2. On any another system connected over a same network... Open browser > type: your hosting pc's IP adress followed by your project name in the url bar. Example: 192.168.72.111/example.com/

Hope it helps! Thanks.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

Markdown `native` text alignment

I known this isn't markdown, but <p align="center"> worked for me, so if anyone figures out the markdown syntax instead I'll be happy to use that. Until then I'll use the HTML tag.

How to get all of the immediate subdirectories in Python

One liner using pathlib:

list_subfolders_with_paths = [p for p in pathlib.Path(path).iterdir() if p.is_dir()]

How to copy from CSV file to PostgreSQL table with headers in CSV file?

Alternative by terminal with no permission

The pg documentation at NOTES say

The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.

So, gerally, using psql or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...

The only way to express relative path with client permissions is using STDIN,

When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.

as remembered here:

psql -h remotehost -d remote_mydb -U myuser -c \
   "copy mytable (column1, column2) from STDIN with delimiter as ','" \
   < ./relative_path/file.csv

CSS /JS to prevent dragging of ghost image?

I think you can change your

img {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}

into a

img {
  -webkit-user-drag: none;
  -khtml-user-drag: none;
  -moz-user-drag: none;
  -o-user-drag: none;
  user-drag: none;
}

How to check if a string is numeric?

Simple method:

public boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}


public boolean isOnlyNumber(String value) {
    boolean ret = false;
    if (!isBlank(value)) {
        ret = value.matches("^[0-9]+$");
    }
    return ret;
}

RecyclerView vs. ListView

Major advantage :

ViewHolder is not available by default in ListView. We will be creating explicitly inside the getView(). RecyclerView has inbuilt Viewholder.

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

cast a List to a Collection

List<T> already implements Collection<T> - why would you need to create a new one?

Collection<T> collection = myList;

The error message is absolutely right - you can't directly instantiate an interface. If you want to create a copy of the existing list, you could use something like:

Collection<T> collection = new ArrayList<T>(myList);

Set mouse focus and move cursor to end of input using jQuery

What about in one single line...

$('#txtSample').focus().val($('#txtSample').val());

This line works for me.

package R does not exist

I just ran into this error while using Bazel to build an Android app:

error: package R does not exist
                + mContext.getString(R.string.common_string),
                                      ^
Target //libraries/common:common_paidRelease failed to build
Use --verbose_failures to see the command lines of failed build steps.

Ensure that your android_library/android_binary is using an AndroidManifest.xml with the correct package= attribute, and if you're using the custom_package attribute on android_library or android_binary, ensure that it is spelled out correctly.

Using a RegEx to match IP addresses in Python

""" regex for finding valid ip address """

import re


IPV4 = re.fullmatch('([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d)', '100.1.1.2')

if IPV4:
    print ("Valid IP address")

else:
    print("Invalid IP address")

The remote end hung up unexpectedly while git cloning

I got solution after using below command:

git repack -a -f -d --window=250 --depth=250

Avoid synchronized(this) in Java?

I'll cover each point separately.

  1. Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

    I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

  2. All synchronized methods within the same class use the exact same lock, which reduces throughput

    This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

  3. You are (unnecessarily) exposing too much information

    This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.

How to get param from url in angular 4?

constructor(private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    this.activatedRoute.params.subscribe(paramsId => {
        this.id = paramsId.id;
        console.log(this.id);
    });
  
 }

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Adding following property to your persistence.xml may solve your problem temporarily

<property name="hibernate.enable_lazy_load_no_trans" value="true" />

As @vlad-mihalcea said it's an antipattern and does not solve lazy initialization issue completely, initialize your associations before closing transaction and use DTOs instead.

python: sys is not defined

Move import sys outside of the try-except block:

import sys
try:
    # ...
except ImportError:
    # ...

If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.

sys is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

What is Ad Hoc Query?

Also want to add that ad hoc query is vulnerable to SQL injection attacks. We should try to avoid using it and use parameterized SQLs instead (like PreparedStatement in Java).

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

adb command for getting ip address assigned by operator

To get all IPs (WIFI and data SIM) even on a non-rooted phone in 2019 use:

adb shell ip -o a

The output looks like:

1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever
1: lo    inet6 ::1/128 scope host \       valid_lft forever preferred_lft forever
3: dummy0    inet6 fe80::489c:2ff:fe4a:00005/64 scope link \       valid_lft forever preferred_lft forever
11: rmnet_data1    inet6 fe80::735d:50fb:2e2:0000/64 scope link \       valid_lft forever preferred_lft forever
21: r_rmnet_data0    inet6 fe80::e38:ce2a:523a:0000/64 scope link \       valid_lft forever preferred_lft forever
30: wlan0    inet 192.168.178.0/24 brd 192.168.178.255 scope global wlan0\       valid_lft forever preferred_lft forever
30: wlan0    inet6 fe80::c2ee:fbff:fe4a:0000/64 scope link \       valid_lft forever preferred_lft forever

You can connect either through adb shell or run the comman ip -o a directly in a terminal emulator. Again, no root required.

How to change the icon of .bat file programmatically?

try with shortcutjs.bat to create a shortcut:

call shortcutjs.bat -linkfile mybat3.lnk -target "%cd%\Ascii2All.bat" -iconlocation "%SystemRoot%\System32\SHELL32.dll,77"

you can use the -iconlocation switch to point to a icon .

What's the difference between ASCII and Unicode?

Understanding why ASCII and Unicode were created in the first place helped me understand the differences between the two.

ASCII, Origins

As stated in the other answers, ASCII uses 7 bits to represent a character. By using 7 bits, we can have a maximum of 2^7 (= 128) distinct combinations*. Which means that we can represent 128 characters maximum.

Wait, 7 bits? But why not 1 byte (8 bits)?

The last bit (8th) is used for avoiding errors as parity bit. This was relevant years ago.

Most ASCII characters are printable characters of the alphabet such as abc, ABC, 123, ?&!, etc. The others are control characters such as carriage return, line feed, tab, etc.

See below the binary representation of a few characters in ASCII:

0100101 -> % (Percent Sign - 37)
1000001 -> A (Capital letter A - 65)
1000010 -> B (Capital letter B - 66)
1000011 -> C (Capital letter C - 67)
0001101 -> Carriage Return (13)

See the full ASCII table over here.

ASCII was meant for English only.

What? Why English only? So many languages out there!

Because the center of the computer industry was in the USA at that time. As a consequence, they didn't need to support accents or other marks such as á, ü, ç, ñ, etc. (aka diacritics).

ASCII Extended

Some clever people started using the 8th bit (the bit used for parity) to encode more characters to support their language (to support "é", in French, for example). Just using one extra bit doubled the size of the original ASCII table to map up to 256 characters (2^8 = 256 characters). And not 2^7 as before (128).

10000010 -> é (e with acute accent - 130)
10100000 -> á (a with acute accent - 160)

The name for this "ASCII extended to 8 bits and not 7 bits as before" could be just referred as "extended ASCII" or "8-bit ASCII".

As @Tom pointed out in his comment below there is no such thing as "extended ASCII" yet this is an easy way to refer to this 8th-bit trick. There are many variations of the 8-bit ASCII table, for example, the ISO 8859-1, also called ISO Latin-1.

Unicode, The Rise

ASCII Extended solves the problem for languages that are based on the Latin alphabet... what about the others needing a completely different alphabet? Greek? Russian? Chinese and the likes?

We would have needed an entirely new character set... that's the rational behind Unicode. Unicode doesn't contain every character from every language, but it sure contains a gigantic amount of characters (see this table).

You cannot save text to your hard drive as "Unicode". Unicode is an abstract representation of the text. You need to "encode" this abstract representation. That's where an encoding comes into play.

Encodings: UTF-8 vs UTF-16 vs UTF-32

This answer does a pretty good job at explaining the basics:

  • UTF-8 and UTF-16 are variable length encodings.
  • In UTF-8, a character may occupy a minimum of 8 bits.
  • In UTF-16, a character length starts with 16 bits.
  • UTF-32 is a fixed length encoding of 32 bits.

UTF-8 uses the ASCII set for the first 128 characters. That's handy because it means ASCII text is also valid in UTF-8.

Mnemonics:

  • UTF-8: minimum 8 bits.
  • UTF-16: minimum 16 bits.
  • UTF-32: minimum and maximum 32 bits.

Note:

Why 2^7?

This is obvious for some, but just in case. We have seven slots available filled with either 0 or 1 (Binary Code). Each can have two combinations. If we have seven spots, we have 2 * 2 * 2 * 2 * 2 * 2 * 2 = 2^7 = 128 combinations. Think about this as a combination lock with seven wheels, each wheel having two numbers only.

Source: Wikipedia, this great blog post and Mocki.co where I initially posted this summary.

EF LINQ include multiple and nested entities

You can also try

db.Courses.Include("Modules.Chapters").Single(c => c.Id == id);

Git: How to find a deleted file in the project commit history?

If you do not know the exact path you may use

git log --all --full-history -- "**/thefile.*"

If you know the path the file was at, you can do this:

git log --all --full-history -- <path-to-file>

This should show a list of commits in all branches which touched that file. Then, you can find the version of the file you want, and display it with...

git show <SHA> -- <path-to-file>

Or restore it into your working copy with:

git checkout <SHA>^ -- <path-to-file>

Note the caret symbol (^), which gets the checkout prior to the one identified, because at the moment of <SHA> commit the file is deleted, we need to look at the previous commit to get the deleted file's contents

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
    <table>
        <tbody>
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>
            </tr>
        </tbody>
    </table>
</div>

How to make a background 20% transparent on Android

You can try to do something like:

textView.getBackground().setAlpha(51);

Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.

The model backing the 'ApplicationDbContext' context has changed since the database was created

From the Tools menu, click NuGet Package Manger, then click Package Manager Console (PMC). Enter the following commands in the PMC.

Enable-Migrations Add-Migration Init Update-Database Run the application. The solution to the problem is from here

Javascript use variable as object name

The object exists in some scope, so you can almost always access the variable via this syntax:

var objname = "myobject";
containing_scope_reference[objname].some_property = 'some value';

The only place where this gets tricky is when you are in a closed scope and you want access to a top-level local variable. When you have something like this:

(function(){
    var some_variable = {value: 25};
    var x = "some_variable";
    console.log(this[x], window[x]); // Doesn't work
})();

You can get around that by using eval instead to access the current scope chain ... but I don't recommend it unless you've done a lot of testing and you know that that's the best way to go about things.

(function(){
    var some_variable = {value: 25};
    var x = "some_variable";
    eval(x).value = 42;
    console.log(some_variable); // Works
})();

Your best bet is to have a reference to a name in an always-going-to-be-there object (like this in the global scope or a private top-level variable in a local scope) and put everything else in there.

Thus:

var my_outer_variable = {};
var outer_pointer = 'my_outer_variable';
// Reach my_outer_variable with this[outer_pointer]
// or window[outer_pointer]

(function(){
    var my_inner_scope = {'my_inner_variable': {} };
    var inner_pointer = 'my_inner_variable';
    // Reach my_inner_variable by using
    // my_inner_scope[inner_pointer]
})();

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

How do you change the size of figures drawn with matplotlib?

You can simply use (from matplotlib.figure.Figure):

fig.set_size_inches(width,height)

As of Matplotlib 2.0.0, changes to your canvas will be visible immediately, as the forward keyword defaults to True.

If you want to just change the width or height instead of both, you can use

fig.set_figwidth(val) or fig.set_figheight(val)

These will also immediately update your canvas, but only in Matplotlib 2.2.0 and newer.

For Older Versions

You need to specify forward=True explicitly in order to live-update your canvas in versions older than what is specified above. Note that the set_figwidth and set_figheight functions don’t support the forward parameter in versions older than Matplotlib 1.5.0.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A C# version of Miroslav Zadravec's code

for (int i = 0; i < dataGridView1.Columns.Count-1; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int colw = dataGridView1.Columns[i].Width;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dataGridView1.Columns[i].Width = colw;
}

Posted as Community Wiki so as to not mooch off of the reputation of others

How to Clear Console in Java?

Runtime.getRuntime().exec("PlatformDepedentCode");

You need to replace "PlatformDependentCode" with your platform's clear console command.

The exec() method executes the command you entered as the argument, just as if it is entered in the console.

In Windows you would write it as Runtime.getRuntime().exec("cls");.

How do I best silence a warning about unused variables?

I have seen this instead of the (void)param2 way of silencing the warning:

void foo(int param1, int param2)
{
    std::ignore = param2;
    bar(param1);
}

Looks like this was added in C++11

How do you share code between projects/solutions in Visual Studio?

Two main steps involved are

1- Creating a C++ dll

In visual studio

New->Project->Class Library in c++ template. Name of project here is first_dll in 
visual studio 2010. Now declare your function as public in first_dll.h file and 
write the code in first_dll.cpp file as shown below.

Header File code

// first_dll.h

using namespace System;

namespace first_dll 
{

public ref class Class1
{
public:
    static double sum(int ,int );
    // TODO: Add your methods for this class here.
};
}

Cpp File

//first_dll.cpp
#include "stdafx.h"

#include "first_dll.h"

namespace first_dll
{

    double Class1:: sum(int x,int y)
    {
        return x+y;
    }

 }

Check This

**Project-> Properties -> Configuration/General -> Configuration Type** 

this option should be Dynamic Library(.dll) and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path 
where first_dll.dll is created and add the file.

Add this line at top in C# project

Using first_dll; 

Now function from dll can be accessed using below statement in some function

double var = Class1.sum(4,5);

I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.

jQuery val is undefined?

I just ran across this myself yesterday on a project I was working on. I'm my specific case, it was not exactly what the input was named, but how the ID was named.

<input id="user_info[1][last_name]" ..... />
var last_name = $("#user_info[1][last_name]").val() // returned undefined

Removing the brackets solved the issue:

<input id="user_info1_last_name" ..... />
var last_name = $("#user_info1_last_name").val() // returned "MyLastNameValue"

Anyway, probably a no brainer for some people, but in case this helps anyone else... there you go!

:-) - Drew

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

How to delete duplicate rows in SQL Server?

With reference to https://support.microsoft.com/en-us/help/139444/how-to-remove-duplicate-rows-from-a-table-in-sql-server

The idea of removing duplicate involves

  • a) Protecting those rows that are not duplicate
  • b) Retain one of the many rows that qualified together as duplicate.

Step-by-step

  • 1) First identify the rows those satisfy the definition of duplicate and insert them into temp table, say #tableAll .
  • 2) Select non-duplicate(single-rows) or distinct rows into temp table say #tableUnique.
  • 3) Delete from source table joining #tableAll to delete the duplicates.
  • 4) Insert into source table all the rows from #tableUnique.
  • 5) Drop #tableAll and #tableUnique

Why does Boolean.ToString output "True" and not "true"

How is it not compatible with C#? Boolean.Parse and Boolean.TryParse is case insensitive and the parsing is done by comparing the value to Boolean.TrueString or Boolean.FalseString which are "True" and "False".

EDIT: When looking at the Boolean.ToString method in reflector it turns out that the strings are hard coded so the ToString method is as follows:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

PHP "pretty print" json_encode

Here's a function to pretty up your json: pretty_json