Programs & Examples On #Xargs

xargs is a command on Unix and most Unix-like operating systems used to build and execute command lines from standard input.

How can I use xargs to copy files that have spaces and quotes in their names?

I created a small portable wrapper script called "xargsL" around "xargs" which addresses most of the problems.

Contrary to xargs, xargsL accepts one pathname per line. The pathnames may contain any character except (obviously) newline or NUL bytes.

No quoting is allowed or supported in the file list - your file names may contain all sorts of whitespace, backslashes, backticks, shell wildcard characters and the like - xargsL will process them as literal characters, no harm done.

As an added bonus feature, xargsL will not run the command once if there is no input!

Note the difference:

$ true | xargs echo no data
no data

$ true | xargsL echo no data # No output

Any arguments given to xargsL will be passed through to xargs.

Here is the "xargsL" POSIX shell script:

#! /bin/sh
# Line-based version of "xargs" (one pathname per line which may contain any
# amount of whitespace except for newlines) with the added bonus feature that
# it will not execute the command if the input file is empty.
#
# Version 2018.76.3
#
# Copyright (c) 2018 Guenther Brunthaler. All rights reserved.
#
# This script is free software.
# Distribution is permitted under the terms of the GPLv3.

set -e
trap 'test $? = 0 || echo "$0 failed!" >& 2' 0

if IFS= read -r first
then
        {
                printf '%s\n' "$first"
                cat
        } | sed 's/./\\&/g' | xargs ${1+"$@"}
fi

Put the script into some directory in your $PATH and don't forget to

$ chmod +x xargsL

the script there to make it executable.

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

Running multiple commands with xargs

You can use

cat file.txt | xargs -i  sh -c 'command {} | command2 {} && command3 {}'

{} = variable for each line on the text file

Make xargs handle filenames that contain spaces

find . -name 'Lemon*.mp3' -print0 | xargs -­0 -i mplayer '{}' 

This helped in my case to delete different files with spaces. It should work too with mplayer. The necessary trick is the quotes. (Tested on Linux Xubuntu 14.04.)

Make xargs execute the command once for each line of input

In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.

I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".

ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.

SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.

Jquery .on('scroll') not firing the event while scrolling

Binding the scroll event after the ul has loaded using ajax has solved the issue. In my findings $(document).on( 'scroll', '#id', function () {...}) is not working and binding the scroll event after the ajax load found working.

$("#ulId").bind('scroll', function() {
   console.log('Event worked');
}); 

You may unbind the event after removing or replacing the ul.

Hope it may help someone.

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

how to add key value pair in the JSON object already declared

you can do try lodash

Example code for json object:

_x000D_
_x000D_
    var user = {'user':'barney','age':36};
    user["newKey"] = true;
    console.log(user);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

for json array elements

Example code:

_x000D_
_x000D_
var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

users.map(i=>{i["newKey"] = true});

console.log(users);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

Check whether a string matches a regex in JS

 let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 let regexp = /[a-d]/gi;
 console.log(str.match(regexp));

Get only the Date part of DateTime in mssql

Another nifty way is:

DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))

Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.

Edit - other date calculations:

First Day of Month:

DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)

First Day of the Year:

DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)

First Day of the Quarter:

DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)

Last Day of Prior Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))

Last Day of Current Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))

Last Day of Current Year:

DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))

First Monday of the Month:

DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)        

Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.

Using Python, how can I access a shared folder on windows network?

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

Is there a way to get the source code from an APK file?

apktool is THE way to go. Online apktool service exists as well: http://www.javadecompilers.com/apktool

Some limitations, obviously, exist due to the service ‘online nature’: you may extract and research assets and the manifest file, but it is impossible to recompile the application at the moment.

Still, this is a no-hassle way to 'open' the android application.

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url https://github.com/abc/abc.git

To see the existing URL just do:

git config remote.origin.url

Publish to IIS, setting Environment Variable

I have modified the answer which @Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.

  1. First, create appsettings.json file in root directory. with the content

      {
         // Possible string values reported below. When empty it use ENV 
            variable value or Visual Studio setting.
         // - Production
         // - Staging
         // - Test
        // - Development
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
    
  2. Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.

  3. Add necessary code to set up the environment to Program.cs file.

    public class Program
    {
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    
      ***var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
    
        try
        {
            ***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of setup related exception");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }
    
    public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog()
            ***.UseEnvironment(enviromentValue);***
    

    }

  4. Add the envsettings.json to your .csproj file for copy to published directory.

       <ItemGroup>
            <None Include="envsettings.json" CopyToPublishDirectory="Always" />
        </ItemGroup>
    
  5. Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

Use the website mentioned in previous posts to create the icons:http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html Unzip folder and Go into you file explorer on (windows or mac) find AndroidStudioProjects > "app name" > app > src > main (replace the web one here)> res (replace the rest with the one from the unzipped folder the you already downloaded)

*Close android studio so that you can make changes and when android studio is opened again the changes will appear

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

A very simple flex solution that does not assume fixed heights or changing position of elements.

HTML

<div class="container">
  <header></header>
  <main></main>
  <footer></footer>
</div>

CSS

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

main {
  flex: 1;
}

Browser Support

All major browsers, except IE11 and below.

Make sure to use Autoprefixer for appropriate prefixes.

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-box;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  -webkit-box-orient: vertical;_x000D_
  -webkit-box-direction: normal;_x000D_
  -ms-flex-direction: column;_x000D_
  flex-direction: column;_x000D_
  min-height: 100vh;_x000D_
}_x000D_
_x000D_
main {_x000D_
  -webkit-box-flex: 1;_x000D_
  -ms-flex: 1;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
/////////////////////////////////////////////_x000D_
_x000D_
body,_x000D_
html {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
header,_x000D_
main,_x000D_
footer {_x000D_
  margin: 0;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
header,_x000D_
footer {_x000D_
  min-height: 80px; _x000D_
}_x000D_
_x000D_
header {_x000D_
  background-color: #ccc;_x000D_
}_x000D_
_x000D_
main {_x000D_
  background-color: #f4f4f4;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: orange;_x000D_
}
_x000D_
<div class="container">_x000D_
  <header></header>_x000D_
  <main></main>_x000D_
  <footer></footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

Xcode 10 Error: Multiple commands produce

For those using React Native and Cocoapods

The issue was produced by some libRN...a files. I fixed it by removing some of them like libRNScreens.a and libRNGestureHandler.a from Build Phases -> Link Binary with Libraries since they were already being referenced from another libraries. Others had to be replaced by their Pod version like libRNDeviceInfo.a:

enter image description here enter image description here

How to suppress scientific notation when printing float values?

This is using Captain Cucumber's answer, but with 2 additions.

1) allowing the function to get non scientific notation numbers and just return them as is (so you can throw a lot of input that some of the numbers are 0.00003123 vs 3.123e-05 and still have function work.

2) added support for negative numbers. (in original function, a negative number would end up like 0.0000-108904 from -1.08904e-05)

def getExpandedScientificNotation(flt):
    was_neg = False
    if not ("e" in flt):
        return flt
    if flt.startswith('-'):
        flt = flt[1:]
        was_neg = True 
    str_vals = str(flt).split('e')
    coef = float(str_vals[0])
    exp = int(str_vals[1])
    return_val = ''
    if int(exp) > 0:
        return_val += str(coef).replace('.', '')
        return_val += ''.join(['0' for _ in range(0, abs(exp - len(str(coef).split('.')[1])))])
    elif int(exp) < 0:
        return_val += '0.'
        return_val += ''.join(['0' for _ in range(0, abs(exp) - 1)])
        return_val += str(coef).replace('.', '')
    if was_neg:
        return_val='-'+return_val
    return return_val

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

How to center horizontally div inside parent div

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

Convert Float to Int in Swift

Most of the solutions presented here would crash for large values and should not be used in production code.

If you don't care for very large values use this code to clamp the Double to max/min Int values.

let bigFloat   = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat

extension Float {
    func toIntTruncated() -> Int {
        let maxTruncated  = min(self, Float(Int.max).nextDown)
        let bothTruncated = max(maxTruncated, Float(Int.min))
        return Int(bothTruncated)
    }
}

// This crashes:
// let bigInt = Int(bigFloat)

// this works for values up to 9223371487098961920
let bigInt   = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()

Print in new line, java

You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.

Since Java 1.7

System.lineSeparator()

Pre Java 1.7

System.getProperty("line.separator")

How to have the cp command create any necessary folders for copying a file to a destination

There is no such option. What you can do is to run mkdir -p before copying the file

I made a very cool script you can use to copy files in locations that doesn't exist

#!/bin/bash
if [ ! -d "$2" ]; then
    mkdir -p "$2"
fi
cp -R "$1" "$2"

Now just save it, give it permissions and run it using

./cp-improved SOURCE DEST

I put -R option but it's just a draft, I know it can be and you will improve it in many ways. Hope it helps you

How many characters can a Java String have?

Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions

"webxml attribute is required" error in Maven

I have had the same error on the test server but not in local. After a few minutes, I discovered that the IDE wasn't synchronized with the pom.xml. Here is how I solve it:

Re-Generate the deployment descriptor with Eclipse

  1. Right click on your project folder
  2. In the contextual menu, choose "Java EE Tools" then "Generate Deployment Descriptor Stub" Generate web.xml
  3. It will create the web.xml. web.xml in project structure

Re-Generate the deployment descriptor with IntelliJ

  1. Right click on your project folder
  2. In the contextual menu, choose "Open Module Settings", then click on the + to add the web deployment descriptor. Generate the deployment descriptor
  3. Then your can change the path to your descriptor or the Web Ressource Directoriesand the on the right side.
  4. Then you will get something like: Project structure

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

MySQL set current date in a DATETIME field on insert

Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.

See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Spring Boot + JPA : Column name annotation ignored

Turns out that I just have to convert @column name testName to all small letters, since it was initially in camel case.

Although I was not able to use the official answer, the question was able to help me solve my problem by letting me know what to investigate.

Change:

@Column(name="testName")
private String testName;

To:

@Column(name="testname")
private String testName;

Copying sets Java

Another way to do this is to use the copy constructor:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);

Or create an empty set and add the elements:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);

Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.


Note that the result of copying a Set is a new Set containing references to the objects that are elements if the original Set. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection APIs are designed to work: they don't copy the element objects.

String field value length in mongoDB

I had a similar kind of scenario, but in my case string is not a 1st level attribute. It is inside an object. In here I couldn't find a suitable answer for it. So I thought to share my solution with you all(Hope this will help anyone with a similar kind of problem).

Parent Collection 

{
"Child":
{
"name":"Random Name",
"Age:"09"
}
}

Ex: If we need to get only collections that having child's name's length is higher than 10 characters.

 db.getCollection('Parent').find({$where: function() { 
for (var field in this.Child.name) { 
    if (this.Child.name.length > 10) 
        return true;

}
}})

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Change selected value of kendo ui dropdownlist

Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.

Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.

To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.

@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
    .Name("Status.StatusId")
    .DataTextField("StatusName")
    .DataValueField("StatusId")
    .BindTo(...)
)

//So that your ViewModel gets bound properly on the post, naming is a bit 
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');    

ddl.select(function(dataItem) {
    return dataItem.StatusName === "Active";
});

How do I see the current encoding of a file in Sublime Text?

Since this thread is a popular result in google search, here is the way to do it for sublime text 3 build 3059+: in user preferences, add the line:

"show_encoding": true

Throw away local commits in Git

Remove untracked files (uncommitted local changes)

git clean -df

Permanently deleting all local commits and get latest remote commit

git reset --hard origin/<branch_name>

MySQL Removing Some Foreign keys

You can not drop the foreign key column because it is being referenced from the table assignmentStuff. So you should first drop the foreign key constraint assignmentStuff.assignmentIDX.

A similar question has already been asked here. Check also here for more info.

Why should Java 8's Optional not be used in arguments

I believe the reson of being is you have to first check whether or not Optional is null itself and then try to evaluate value it wraps. Too many unnecessary validations.

What jsf component can render a div tag?

You can create a DIV component using the <h:panelGroup/>. By default, the <h:panelGroup/> will generate a SPAN in the HTML code.

However, if you specify layout="block", then the component will be a DIV in the generated HTML code.

<h:panelGroup layout="block"/>

Generating random numbers in Objective-C

As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.

You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.

At the simplest level, you can generate a random number from the system's built-in random source like this:

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

Plus you can shape the random distribution by using things like GKShuffledDistribution.

NSURLErrorDomain error codes description

I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain taken from NSURLError.h

/*!
    @enum NSURL-related Error Codes
    @abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
    NSURLErrorUnknown =             -1,
    NSURLErrorCancelled =           -999,
    NSURLErrorBadURL =              -1000,
    NSURLErrorTimedOut =            -1001,
    NSURLErrorUnsupportedURL =          -1002,
    NSURLErrorCannotFindHost =          -1003,
    NSURLErrorCannotConnectToHost =         -1004,
    NSURLErrorNetworkConnectionLost =       -1005,
    NSURLErrorDNSLookupFailed =         -1006,
    NSURLErrorHTTPTooManyRedirects =        -1007,
    NSURLErrorResourceUnavailable =         -1008,
    NSURLErrorNotConnectedToInternet =      -1009,
    NSURLErrorRedirectToNonExistentLocation =   -1010,
    NSURLErrorBadServerResponse =       -1011,
    NSURLErrorUserCancelledAuthentication =     -1012,
    NSURLErrorUserAuthenticationRequired =  -1013,
    NSURLErrorZeroByteResource =        -1014,
    NSURLErrorCannotDecodeRawData =             -1015,
    NSURLErrorCannotDecodeContentData =         -1016,
    NSURLErrorCannotParseResponse =             -1017,
    NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
    NSURLErrorFileDoesNotExist =        -1100,
    NSURLErrorFileIsDirectory =         -1101,
    NSURLErrorNoPermissionsToReadFile =     -1102,
    NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

    // SSL errors
    NSURLErrorSecureConnectionFailed =      -1200,
    NSURLErrorServerCertificateHasBadDate =     -1201,
    NSURLErrorServerCertificateUntrusted =  -1202,
    NSURLErrorServerCertificateHasUnknownRoot = -1203,
    NSURLErrorServerCertificateNotYetValid =    -1204,
    NSURLErrorClientCertificateRejected =   -1205,
    NSURLErrorClientCertificateRequired =   -1206,
    NSURLErrorCannotLoadFromNetwork =       -2000,

    // Download and file I/O errors
    NSURLErrorCannotCreateFile =        -3000,
    NSURLErrorCannotOpenFile =          -3001,
    NSURLErrorCannotCloseFile =         -3002,
    NSURLErrorCannotWriteToFile =       -3003,
    NSURLErrorCannotRemoveFile =        -3004,
    NSURLErrorCannotMoveFile =          -3005,
    NSURLErrorDownloadDecodingFailedMidStream = -3006,
    NSURLErrorDownloadDecodingFailedToComplete =-3007,

    NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
    NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
    NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
    NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

    NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
    NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
    NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

If you want to allow Html tags only for few textbox in mvc

You can do one thing

in controller

 [ValidateInput(false)]
public ActionResult CreateNewHtml()  //view
{
    return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
    repo.AddHtml(obj);
    return View();
}

Why am I seeing "TypeError: string indices must be integers"?

The variable item is a string. An index looks like this:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

The above example uses the 0 index of the string to refer to the first character.

Strings can't have string indices (like dictionaries can). So this won't work:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers

Working Copy Locked

I ended up using export command rather than update command. This is the post-commit hook

"C:\Program Files\VisualSVN Server\bin\svn.exe" export "D:\xampp\htdocs\test-lalala" --quiet --non-interactive --force --username myusername --password mypassword

C++ catching all exceptions

Someone should add that one cannot catch "crashes" in C++ code. Those don't throw exceptions, but do anything they like. When you see a program crashing because of say a null-pointer dereference, it's doing undefined behavior. There is no std::null_pointer_exception. Trying to catch exceptions won't help there.

Just for the case someone is reading this thread and thinks he can get the cause of the program crashes. A Debugger like gdb should be used instead.

How to get just one file from another branch

Supplemental to VonC's and chhh's answers.

git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative than just use
git show experiment:app.js > app.js

or

git checkout experiment -- app.js

Seeding the random number generator in Javascript

No, but here's a simple pseudorandom generator, an implementation of Multiply-with-carry I adapted from Wikipedia (has been removed since):

var m_w = 123456789;
var m_z = 987654321;
var mask = 0xffffffff;

// Takes any integer
function seed(i) {
    m_w = (123456789 + i) & mask;
    m_z = (987654321 - i) & mask;
}

// Returns number between 0 (inclusive) and 1.0 (exclusive),
// just like Math.random().
function random()
{
    m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
    m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
    var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
    result /= 4294967296;
    return result;
}

EDIT: fixed seed function by making it reset m_z
EDIT2: Serious implementation flaws have been fixed

How do I add a library path in cmake?

You had better use find_library command instead of link_directories. Concretely speaking there are two ways:

  1. designate the path within the command

    find_library(NAMES gtest PATHS path1 path2 ... pathN)

  2. set the variable CMAKE_LIBRARY_PATH

    set(CMAKE_LIBRARY_PATH path1 path2)
    find_library(NAMES gtest)

the reason is as flowings:

Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).

Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).

If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.

nodejs vs node on ubuntu 12.04

If you are on an AWS EC2 instance running an Ubuntu instance (tested on Ubuntu 16.x), then these steps might work for you:

    sudo apt-get update
    sudo apt-get --purge remove node -y
    sudo apt-get --purge remove nodejs -y
    sudo apt-get --purge remove legacy-node -y
    sudo rm  /usr/bin/node
    curl -sL https://deb.nodesource.com/setup_6.x | sudo bash -
    sudo apt-get install nodejs -y
    node -v

If all is correct the last command shall have an output like : v6.x.x

If not then run the following:

    sudo ln -s /usr/bin/nodejs /usr/bin/node

Hopefully this will help. It helped me magically (hehe).

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Full width layout with twitter bootstrap

As of the latest Bootstrap (3.1.x), the way to achieve a fluid layout it to use .container-fluid class.

See Bootstrap grid for reference

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

"No suitable driver" usually means that the JDBC URL you've supplied to connect has incorrect syntax or when the driver isn't loaded at all.

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.(using Class.forName())

For Example

import oracle.jdbc.driver.OracleDriver;

Class.forName("oracle.jdbc.driver.­OracleDriver");

Also check that you have ojdbc6.jar in your classpath. I would suggest to place .jar at physical location to JBoss "$JBOSS_HOME/server/default/lib/" directory of your project.

EDIT:

You have mentioned hibernate lately.

Check that your hibernate.cfg.xml file has connection properties something like this:

<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

How to insert an item into an array at a specific index (JavaScript)?

Another possible solution, with usage of Array#reduce.

_x000D_
_x000D_
const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];

const insert = (arr, item, index) =>
  arr.reduce(function(s, a, i) {
    i === index ? s.push(item, a) : s.push(a);
    return s;
  }, []); 

console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))
_x000D_
_x000D_
_x000D_

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

How to Toggle a div's visibility by using a button click

with JQuery .toggle() you can accomplish it easily

$( ".target" ).toggle();

vb.net get file names in directory?

Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String

For Each fileName In fileEntries
    If (System.IO.File.Exists(fileName)) Then
        'Read File and Print Result if its true
        ReadFile(fileName)
    End If
    TransfereFile(fileName, 1)
Next

jquery background-color change on focus and blur

Even easier, just CSS can resolve the problem:

input[type="text"], input[type="password"], textarea, select { 
    width: 200px;
    border: 1px solid;
    border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
    background: #FFF;
    padding: 8px 5px;
    font: 16px Arial, Tahoma, Helvetica, sans-serif;
    -moz-box-shadow: 0 0 5px #C0C0C0;
    -moz-border-radius: 5px;
    -webkit-box-shadow: 0 0 5px #C0C0C0;
    -webkit-border-radius: 5px;
    box-shadow: 0 0 5px #C0C0C0;
    border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus { 
    border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
    outline: none;
    -moz-box-shadow: 0 0 10px #B6D5F7;
    -webkit-box-shadow: 0 0 10px #B6D5F7;
    box-shadow: 0 0 10px #B6D5F7;
}

Creating a JSON response using Django and Python

Its very convenient with Django version 1.7 or higher as you have the JsonResponse class, which is a subclass of HttpResponse.

from django.http import JsonResponse
    def profile(request):
        data = {
            'name': 'Raghav',
            'location': 'India',
            'is_active': False,
            'count': 28
        }
        return JsonResponse(data)

For older versions of Django, you must use an HttpResponse object.

import json
from django.http import HttpResponse

def profile(request):
    data = {
        'name': 'Raghav',
        'location': 'India',
        'is_active': False,
        'count': 28
    }
    dump = json.dumps(data)
    return HttpResponse(dump, content_type='application/json')

How do I check if string contains substring?

Another way:

var testStr = "This is a test";

if(testStr.contains("test")){
    alert("String Found");
}

** Tested on Firefox, Safari 6 and Chrome 36 **

How to make exe files from a node.js app?

There a few alternatives, both free and commercial. I haven't used any of them but in theory they should work:

Most will require you to keep the batch file as main executable, and then bundle node.exe and your scripts.

Depending on your script, you also have the option to port it to JSDB, which supports an easy way to create executables by simply appending resources to it.

A third quasi-solution is to keep node somewhere like C:\utils and add this folder to your PATH environment variable. Then you can create .bat files in that dir that run node + your preferred scripts - I got coffeescript's coffee working on windows this way. This setup can be automated with a batch file, vb script or installer.

get UTC time in PHP

You can use gmmktime function without arguments to obtain the current UTC timestamp:

$time = gmmktime();
echo date("Y-m-d H:i:s", $time); 

gmmktime will only work if your server time is using UTC. For example, my server is set to US/Pacific. the listed function above echos back Pacific time.

How best to include other scripts?

A combination of the answers to this question provides the most robust solution.

It worked for us in production-grade scripts with great support of dependencies and directory structure:

#!/bin/bash

# Full path of the current script
THIS=`readlink -f "${BASH_SOURCE[0]}" 2>/dev/null||echo $0`

# The directory where current script resides
DIR=`dirname "${THIS}"`

# 'Dot' means 'source', i.e. 'include':
. "$DIR/compile.sh"

The method supports all of these:

  • Spaces in path
  • Links (via readlink)
  • ${BASH_SOURCE[0]} is more robust than $0

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Is your server configured for client authentication? If so you need to pass the client certificate while connecting with the server.

How to use "svn export" command to get a single file from the repository?

For the substition impaired here is a real example from GitHub.com to a local directory:

svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces
svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces /temp/SvnExport/Washburn

See: Download a single folder or directory from a GitHub repo for more details.

Iterating on a file doesn't work the second time

The file object is a buffer. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the end of the file (EOF), so it returns nothing because there is nothing left to read.

If you have to reset the read position on a file object for some reason, you can do:

f.seek(0)

TensorFlow: "Attempting to use uninitialized value" in variable initialization

There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
    else:
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

You should change to following

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as 
    # NOT RUNNING BUT ASSIGN
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    print([op.name for op in g.get_operations()])
    # ONLY EVAL AFTER INIT
    print(l.eval(session=sess))

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to post object and List using postman

//backend.

@PostMapping("/")
public List<A> addList(@RequestBody A aObject){
//......ur code
}

class A{
int num;
String name;
List<B> bList;
//getters and setters and default constructor
}
class B{
int d;
//defalut Constructor & gettes&setters
}

// postman

{
"num":value,
"name":value,
"bList":[{
"key":"value",
"key":"value",.....
}]
}
  1. the error is for list there is no default constructor .so we can keep our list of object as a property of another class and pass the list of objects through the postman as the parameter of the another class.

Django request.GET

Calling /search/ should result in "you submitted nothing", but calling /search/?q= on the other hand should result in "you submitted u''"

Browsers have to add the q= even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:

if request.GET.get('q'):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

How do I divide so I get a decimal value?

If you initialize both the parameters as float, you will sure get actual divided value. For example:

float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;

Ans:17.75.

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

How to output (to a log) a multi-level array in a format that is human-readable?

Simple stuff:

Using print_r, var_dump or var_export should do it pretty nicely if you look at the result in view-source mode not in HTML mode or as @Joel Larson said if you wrap everything in a <pre> tag.

print_r is best for readability but it doesn't print null/false values.

var_dump is best for checking types of values and lengths and null/false values.

var_export is simmilar to var_dump but it can be used to get the dumped string.

The format returned by any of these is indented correctly in the source code and var_export can be used for logging since it can be used to return the dumped string.

Advanced stuff:

Use the xdebug plug-in for PHP this prints var_dumps as HTML formatted strings not as raw dump format and also allows you to supply a custom function you want to use for formatting.

App.Config change value

To update entries other than appsettings, simply use XmlDocument.

public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
    var doc = new XmlDocument();
    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    var tags = doc.GetElementsByTagName(tagName);
    foreach (XmlNode item in tags)
    {
        var attribute = item.Attributes[attributeName];
        if (!ReferenceEquals(null, attribute))
            attribute.Value = value;
    }
    doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

This is how you call it:

Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");

Utility.UpdateAppConfig("network", "host", "abc.com.au");

This method can be improved to cater for appSettings values as well.

Iframe transparent background

<style type="text/css">
body {background:none transparent;
}
</style>

that might work (if you put in the iframe) along with

<iframe src="stuff.htm" allowtransparency="true">

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Forking / Multi-Threaded Processes | Bash

Let me try example

for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } &  done ; sleep 10

And use jobs to see what's running.

ValueError: all the input arrays must have same number of dimensions

(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None] notation:

n_lists = np.append(n_list_converted, n_last[:, None], axis=1)

Alternatively, when extracting n_last you can use

n_last = n_list_converted[:, -1:]

to get a (20, 1) array.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64(uarr) {
    var strings = [], chunksize = 0xffff;
    var len = uarr.length;

    for (var i = 0; i * chunksize < len; i++){
        strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize)));
    }

    return strings.join("");
}

This is better, if you use JSZip for unpack archive from string

Import functions from another js file. Javascript

From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Getting only Month and Year from SQL DATE

let's write it this way: YEAR(anySqlDate) and MONTH(anySqlDate). Try it with YEAR(GETDATE()) for example.

How to do paging in AngularJS?

I've extracted the relevant bits here. This is a 'no frills' tabular pager, so sorting or filtering is not included. Feel free to change/add as needed:

_x000D_
_x000D_
     //your data source may be different. the following line is _x000D_
     //just for demonstration purposes only_x000D_
    var modelData = [{_x000D_
      text: 'Test1'_x000D_
    }, {_x000D_
      text: 'Test2'_x000D_
    }, {_x000D_
      text: 'Test3'_x000D_
    }];_x000D_
_x000D_
    (function(util) {_x000D_
_x000D_
      util.PAGE_SIZE = 10;_x000D_
_x000D_
      util.range = function(start, end) {_x000D_
        var rng = [];_x000D_
_x000D_
        if (!end) {_x000D_
          end = start;_x000D_
          start = 0;_x000D_
        }_x000D_
_x000D_
        for (var i = start; i < end; i++)_x000D_
          rng.push(i);_x000D_
_x000D_
        return rng;_x000D_
      };_x000D_
_x000D_
      util.Pager = function(data) {_x000D_
        var self = this,_x000D_
          _size = util.PAGE_SIZE;;_x000D_
_x000D_
        self.current = 0;_x000D_
_x000D_
        self.content = function(index) {_x000D_
          var start = index * self.size,_x000D_
            end = (index * self.size + self.size) > data.length ? data.length : (index * self.size + self.size);_x000D_
_x000D_
          return data.slice(start, end);_x000D_
        };_x000D_
_x000D_
        self.next = function() {_x000D_
          if (!self.canPage('Next')) return;_x000D_
          self.current++;_x000D_
        };_x000D_
_x000D_
        self.prev = function() {_x000D_
          if (!self.canPage('Prev')) return;_x000D_
          self.current--;_x000D_
        };_x000D_
_x000D_
        self.canPage = function(dir) {_x000D_
          if (dir === 'Next') return self.current < self.count - 1;_x000D_
          if (dir === 'Prev') return self.current > 0;_x000D_
          return false;_x000D_
        };_x000D_
_x000D_
        self.list = function() {_x000D_
          var start, end;_x000D_
          start = self.current < 5 ? 0 : self.current - 5;_x000D_
          end = self.count - self.current < 5 ? self.count : self.current + 5;_x000D_
          return Util.range(start, end);_x000D_
        };_x000D_
_x000D_
        Object.defineProperty(self, 'size', {_x000D_
          configurable: false,_x000D_
          enumerable: false,_x000D_
          get: function() {_x000D_
            return _size;_x000D_
          },_x000D_
          set: function(val) {_x000D_
            _size = val || _size;_x000D_
          }_x000D_
        });_x000D_
_x000D_
        Object.defineProperty(self, 'count', {_x000D_
          configurable: false,_x000D_
          enumerable: false,_x000D_
          get: function() {_x000D_
            return Math.ceil(data.length / self.size);_x000D_
          }_x000D_
        });_x000D_
      };_x000D_
_x000D_
    })(window.Util = window.Util || {});_x000D_
_x000D_
    (function(ns) {_x000D_
      ns.SampleController = function($scope, $window) {_x000D_
        $scope.ModelData = modelData;_x000D_
        //instantiate pager with array (i.e. our model)_x000D_
        $scope.pages = new $window.Util.Pager($scope.ModelData);_x000D_
      };_x000D_
    })(window.Controllers = window.Controllers || {});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<table ng-controller="Controllers.SampleController">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        Col1_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr ng-repeat="item in pages.content(pages.current)" title="{{item.text}}">_x000D_
      <td ng-bind-template="{{item.text}}"></td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
  <tfoot>_x000D_
    <tr>_x000D_
      <td colspan="4">_x000D_
        <a href="#" ng-click="pages.prev()">&laquo;</a>_x000D_
        <a href="#" ng-repeat="n in pages.list()" ng-click="pages.current = n" style="margin: 0 2px;">{{n + 1}}</a>_x000D_
        <a href="#" ng-click="pages.next()">&raquo;</a>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tfoot>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I load the contents of a text file into a javascript variable?

One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is

    client.onreadystatechange = function() {

and in danb's case, it is

 function(data) {

This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.

Organizing a multiple-file Go project

I find very useful to understand how to organize code in Golang this chapter http://www.golang-book.com/11 of the book written by Caleb Doxsey

Error on line 2 at column 1: Extra content at the end of the document

You might have output (maybe error/debug output) that precedes your call to

header("Content-type: text/xml");

Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).

Return in Scala

By default the last expression of a function will be returned. In your example there is another expression after the point, where you want your return value. If you want to return anything prior to your last expression, you still have to use return.

You could modify your example like this, to return a Boolean from the first part

def balanceMain(elem: List[Char]): Boolean = {
  if (elem.isEmpty) {
    // == is a Boolean resulting function as well, so your can write it this way
    count == 0
  } else {
    // keep the rest in this block, the last value will be returned as well
    if (elem.head == "(") {
      balanceMain(elem.tail, open, count + 1)
    }
    // some more statements
    ...
    // just don't forget your Boolean in the end
    someBoolExpression
  }
}

Java constructor/method with optional parameters?

You can use varargs for optional parameters:

public class Booyah {
    public static void main(String[] args) {
        woohoo(1);
        woohoo(2, 3);
    }
    static void woohoo(int required, Integer... optional) {
        Integer lala;
        if (optional.length == 1) {
            lala = optional[0];
        } else {
            lala = 2;
        }
        System.out.println(required + lala);
    }
}

Also it's important to note the use of Integer over int. Integer is a wrapper around the primitive int, which allows one to make comparisons with null as necessary.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

Following steps helped me to fix this issue, Solution 1:

  1. git checkout master
  2. git pull
  3. git checkout [you current branch]
  4. git pull

You can also set git config http.postBuffer 524288000 to increase the network buffer

Solution 2:

Sometimes it happens when you are cloning your repo using VPN and it fails to verify the SSL

Try this out it may help:

git config http.sslVerify "false"

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

Where can I find the API KEY for Firebase Cloud Messaging?

STEP 1: Go to Firebase Console

STEP 2: Select your Project

STEP 3: Click on Settings icon and select Project Settings

Select Project Setting

STEP 4: Select CLOUD MESSAGING tab

enter image description here

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

The R Language Definition is handy for answering these types of questions:

R has three basic indexing operators, with syntax displayed by the following examples

    x[i]
    x[i, j]
    x[[i]]
    x[[i, j]]
    x$a
    x$"a"

For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

New lines (\r\n) are not working in email body

OP's problem was related with HTML coding. But if you are using plain text, please use "\n" and not "\r\n".

My personal use case: using mailx mailer, simply replacing "\r\n" into "\n" fixed my issue, related with wrong automatic Content-Type setting.

Wrong header:

User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64

Correct header:

User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

I'm not saying that "application/octet-stream" and "base64" are always wrong/unwanted, but they where in my case.

Difference between Divide and Conquer Algo and Dynamic Programming

  • Divide and Conquer
    • They broke into non-overlapping sub-problems
    • Example: factorial numbers i.e. fact(n) = n*fact(n-1)
fact(5) = 5* fact(4) = 5 * (4 * fact(3))= 5 * 4 * (3 *fact(2))= 5 * 4 * 3 * 2 * (fact(1))

As we can see above, no fact(x) is repeated so factorial has non overlapping problems.

  • Dynamic Programming
    • They Broke into overlapping sub-problems
    • Example: Fibonacci numbers i.e. fib(n) = fib(n-1) + fib(n-2)
fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1))

As we can see above, fib(4) and fib(3) both use fib(2). similarly so many fib(x) gets repeated. that's why Fibonacci has overlapping sub-problems.

  • As a result of the repetition of sub-problem in DP, we can keep such results in a table and save computation effort. this is called as memoization

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

How to split a long array into smaller arrays, with JavaScript

Another implementation, using Array.reduce (I think it’s the only one missing!):

const splitArray = (arr, size) =>
{
    if (size === 0) {
        return [];
    }

    return arr.reduce((split, element, index) => {
        index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
        return split;
    }, []);
};

As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.

How can I delete multiple lines in vi?

d5d "cuts" five lines

I usually just throw the number in the middle like:

d7l = delete 7 letters

How to get the current location latitude and longitude in android

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

How to get a string after a specific substring?

In Python 3.9, a new removeprefix method is being added:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

Get all files that have been modified in git branch

All you have to do is the following:

git checkout <notMainDev>
git diff --name-only <mainDev>

This will show you only the filenames that are different between the two branches.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Android Fragment handle back button press

Create interfaces:

BackButtonHandlerInterface

public interface BackButtonHandlerInterface {
    void addBackClickListener (OnBackClickListener onBackClickListener);
    void removeBackClickListener (OnBackClickListener onBackClickListener);
}

OnBackClickListener

public interface OnBackClickListener {
     boolean onBackClick();
}

In Activity:

public class MainActivity extends AppCompatActivity implements BackButtonHandlerInterface {

    private ArrayList<WeakReference<OnBackClickListener>> backClickListenersList = new ArrayList<>();

    @Override
    public void addBackClickListener(OnBackClickListener onBackClickListener) {
        backClickListenersList.add(new WeakReference<>(onBackClickListener));
    }

    @Override
    public void removeBackClickListener(OnBackClickListener onBackClickListener) {
        for (Iterator<WeakReference<OnBackClickListener>> iterator = backClickListenersList.iterator();
         iterator.hasNext();){
            WeakReference<OnBackClickListener> weakRef = iterator.next();
            if (weakRef.get() == onBackClickListener){
                iterator.remove();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if(!fragmentsBackKeyIntercept()){
            super.onBackPressed();
        }
    }

    private boolean fragmentsBackKeyIntercept() {
        boolean isIntercept = false;
        for (WeakReference<OnBackClickListener> weakRef : backClickListenersList) {
            OnBackClickListener onBackClickListener = weakRef.get();
            if (onBackClickListener != null) {
                boolean isFragmIntercept = onBackClickListener.onBackClick();
                if (!isIntercept) isIntercept = isFragmIntercept;
            }
        }
        return isIntercept;
    }
}

In Fragment:

public class MyFragment extends Fragment implements OnBackClickListener{

    private BackButtonHandlerInterface backButtonHandler;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        backButtonHandler = (BackButtonHandlerInterface) activity;
        backButtonHandler.addBackClickListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        backButtonHandler.removeBackClickListener(this);
        backButtonHandler = null;
    }

    @Override
    public boolean onBackClick() {
        //This method handle onBackPressed()! return true or false
        return false;
    }

}

Update

Provide custom back navigation

class MyFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // This callback will only be called when MyFragment is at least Started.
        val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event
        }

        // The callback can be enabled or disabled here or in the lambda
    }

}

How to get twitter bootstrap modal to close (after initial launch)

According the documentaion hide / toggle should work. But it don't.

Here is how I did it

$('#modal-id').modal('toggle'); //Hide the modal dialog
$('.modal-backdrop').remove(); //Hide the backdrop
$("body").removeClass( "modal-open" ); //Put scroll back on the Body

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2

How to display both icon and title of action inside ActionBar?

'always|withText' will work if there is sufficient room, otherwise it will only place icon. You can test it on your phone with rotation.

<item android:id="@id/menu_item"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Just note that maybe your Entity have primary key but your table in database doesn't have primary key.

Installing a plain plugin jar in Eclipse 3.5

Since the advent of p2, you should be using the dropins directory instead.

To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.

Android - how do I investigate an ANR?

my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...

Duplicate AssemblyVersion Attribute

In my case, there where a subfolder in a project that was a project folder it self:

  • file system:

    • c:\projects\webapi\wepapi.csproj
    • c:\projects\webapi\tests\wepapitests.csproj
  • solution

    • webapi (folder and project)
      • tests (folder)
    • tests (folder and project)

Then i had to remove the subfolder "tests" from the "webapi" project.

Get LatLng from Zip Code - Google Maps API

Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}

Google Geocoding

Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)

EXAMPLE to get lat/lng:

    var lat = '';
    var lng = '';
    var address = {zipcode} or {city and state};
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         lat = results[0].geometry.location.lat();
         lng = results[0].geometry.location.lng();
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    alert('Latitude: ' + lat + ' Logitude: ' + lng);

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

Future Readers

Check each of the following:

  1. The component is declared in a SINGLE angular module
  2. Make sure you have import { CommonModule } from '@angular/common';
  3. Restart the IDE/editor
  4. Restart the dev server (ng serve)

Artificially create a connection timeout error

You can try to connect to one of well-known Web sites on a port that may not be available from outside - 200 for example. Most of firewalls work in DROP mode and it will simulate a timeout for you.

Read values into a shell variable from a pipe

The first attempt was pretty close. This variation should work:

echo "hello world" | { test=$(< /dev/stdin); echo "test=$test"; };

and the output is:

test=hello world

You need braces after the pipe to enclose the assignment to test and the echo.

Without the braces, the assignment to test (after the pipe) is in one shell, and the echo "test=$test" is in a separate shell which doesn't know about that assignment. That's why you were getting "test=" in the output instead of "test=hello world".

ImportError: No module named six

You probably don't have the six Python module installed. You can find it on pypi.

To install it:

$ easy_install six

(if you have pip installed, use pip install six instead)

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

What is the most efficient way to store a list in the Django models?

You can store virtually any object using a Django Pickle Field, ala this snippet:

http://www.djangosnippets.org/snippets/513/

How to get local server host and port in Spring Boot?

For Spring 2

val hostName = InetAddress.getLocalHost().hostName

var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
    override fun onApplicationEvent(event: WebServerInitializedEvent) {
        webServerPort = event.webServer.port
    }
}

then you can use also webServerPort from anywhere...

How to remove index.php from URLs?

This may be old, but I may as well write what I've learned down. So anyway I did it this way.

---------->

Before you start, make sure the Apache rewrites module is enabled and then follow the steps below.

1) Log-in to your Magento administration area then go to System > Configuration > Web.

2) Navigate to the Unsecure and Secure tabs. Make sure the Unsecured and Secure - Base Url options have your domain name within it, and do not leave the forward slash off at the end of the URL. Example: http://www.yourdomain.co.uk/

3) While still on the Web page, navigate to Search Engine Optimisation tab and select YES underneath the Use Web Server Rewrites option.

4) Navigate to the Secure tab again (if not already on it) and select Yes on the Use Secure URLs in Front-End option.

5) Now go to the root of your Magento website folder and use this code for your .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Save the .htaccess and replace the original file. (PLEASE MAKE SURE TO BACKUP YOUR ORIGINAL .htaccess FILE BEFORE MESSING WITH IT!!!)

6) Now go to System > Cache Management and select all fields and make sure the Actions dropdown is set on Refresh, then submit. (This will of-course refresh the Cache.)

---------->

If this did not work please follow these extra steps.

7) Go to System > Configuration > web again. This time look for the Current Configuration Scope and select your website from the dropdown menu. (This is of course, it is set to Default Config)

8) Make sure the Unsecure and Secure fields contain the same domain as the previous Default Config file.

9) Navigate to the Search Engines Optimisation tab and select Yes underneath the Use Web Server Rewrites section.

10) Once the URLs are the same, and the rewrite is enabled save that page, then go back and make sure they are all checked as default, then save again if needed.

11) Repeat step 6.

Now your index.php problem should be fixed and all should be well!!!

I hope this helps, and good luck.

CSS background-image-opacity?

Try this

<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat; background-position: center;"> </div>

Make TextBox uneditable

Using the TextBox.ReadOnly property

TextBox.ReadOnly = true;

For a Non-Grey background you can change the TextBox.BackColor property to SystemColors.Window Color

textBox.BackColor = System.Drawing.SystemColors.Window;

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

How to squash commits in git after they have been pushed?

Minor difference to accepted answer, but I was having a lot of difficulty squashing and finally got it.

$ git rebase -i HEAD~4
  • At the interactive screen that opens up, replace pick with squash at the top for all the commits that you want to squash.
  • Save and close the editor through esc --> :wq

Push to the remote using:

$ git push origin branch-name --force

UPDATE and REPLACE part of a string

For anyone want to replace your script.

update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

Converting time stamps in excel to dates

below formula worked form me in MS EXEL

=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")

CELL_VALUE is timestamp in milliseconds

here is explanation for text function.

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

Programmatically scroll a UIScrollView

With Animation in Swift

scrollView.setContentOffset(CGPointMake(x, y), animated: true)

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In XSLT the same <xsl:variable> can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.

Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="class">
    <xsl:variable name="subexists">
            <xsl:choose>
                <xsl:when test="joined-subclass">true</xsl:when>
                <xsl:otherwise>false</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        subexists:  <xsl:text/>    
        <xsl:value-of select="$subexists" />
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the following XML document:

<class>
 <joined-subclass/>
</class>

the wanted result is produced:

    subexists:  true

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

Messages Using Command prompt in Windows 7

"net send" is a command using a background service called "messenger". This service has been removed from Windows 7. ie You cannot use 'net send' on Vista nor Win7 / Win8.

Pity though , I loved using it.

There is alternatives, but that requires you to download and install software on each pc you want to use, this software runs as background services, and i would advise one to be very very very very careful of using these kind of software as they can potentially cause seriously damage one's system or impair the systems securities.

winsent innocenti / winsent messenger

****This command is risky because of what is stated above***

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Well this is because ArrayList resulting from Arrays.asList() is not of the type java.util.ArrayList . Arrays.asList() creates an ArrayList of type java.util.Arrays$ArrayList which does not extend java.util.ArrayList but only extends java.util.AbstractList

jQuery SVG vs. Raphael

For posterity, I'd like to note that I ended up choosing Raphael, because of the clean API and "free" IE support, and also because the active development looks promising (event support was just added in 0.7, for instance). However, I'll leave the question unanswered, and I'd still be interested to hear about others' experiences using Javascript + SVG libraries.

How to count the number of occurrences of an element in a List

Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it.

HashMap<String,int> frequencymap = new HashMap<String,int>();
foreach(String a in animals) {
  if(frequencymap.containsKey(a)) {
    frequencymap.put(a, frequencymap.get(a)+1);
  }
  else{ frequencymap.put(a, 1); }
}

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

  1. Exception Handling

    try{
        int i = Integer.parseInt(input);
    } catch(NumberFormatException ex){ // handle your exception
        ...
    }
    

or - Integer pattern matching -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}

Send attachments with PHP Mail()?

After struggling for a while with badly formatted attachments, this is the code I used:

$email = new PHPMailer();
$email->From      = '[email protected]';
$email->FromName  = 'FromName';
$email->Subject   = 'Subject';
$email->Body      = 'Body';
$email->AddAddress( '[email protected]' );
$email->AddAttachment( "/path/to/filename.ext" , "filename.ext", 'base64', 'application/octet-stream' );
$email->Send();

Initialising mock objects - MockIto

The other answers are great and contain more detail if you want/need them.
In addition to those, I would like to add a TL;DR:

  1. Prefer to use
    • @RunWith(MockitoJUnitRunner.class)
  2. If you cannot (because you already use a different runner), prefer to use
    • @Rule public MockitoRule rule = MockitoJUnit.rule();
  3. Similar to (2), but you should not use this anymore:
    • @Before public void initMocks() { MockitoAnnotations.initMocks(this); }
  4. If you want to use a mock in just one of the tests and don't want to expose it to other tests in the same test class, use
    • X x = mock(X.class)

(1) and (2) and (3) are mutually exclusive.
(4) can be used in combination with the others.

Why do some functions have underscores "__" before and after the function name?

Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:

class ThreadableMixin:
   def start_worker(self):
       threading.Thread(target=self.worker).start()

   def worker(self):
      try:
        self._worker()
    except tornado.web.HTTPError, e:
        self.set_status(e.status_code)
    except:
        logging.error("_worker problem", exc_info=True)
        self.set_status(500)
    tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))

...

and the child that have a _worker method

class Handler(tornado.web.RequestHandler, ThreadableMixin):
   def _worker(self):
      self.res = self.render_string("template.html",
        title = _("Title"),
        data = self.application.db.query("select ... where object_id=%s", self.object_id)
    )

...

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

first I had to delete my registry by using npm config delete registry and register new value using npm config set registry "http://registry.npmjs.org"

Is there a Java equivalent or methodology for the typedef keyword in C++?

There is no need for typedef in Java. Everything is an Object except for the primitives. There are no pointers, only references. The scenarios where you normally would use typedefs are instances in which you create objects instead.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

When to use LIBXML_NOCDATA ?

I add the issue when transforming XML to JSON.

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo json_encode($xml, true); 
/* prints
   {
     "content": {}
   }
 */

When accessing the SimpleXMLElement object, It gets the CDATA :

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo $xml->content; 
/* prints
   Hello, world!
*/

I makes sense to use LIBXML_NOCDATA because json_encode don't access the SimpleXMLElement to trigger the string casting feature, I'm guessing a __toString() equivalent.

$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>", null, LIBXML_NOCDATA);
echo json_encode($xml);
/*
 {
   "content": "Hello, world!"
 }
*/

How to update core-js to core-js@3 dependency?

For ng9 upgraders:

npm i -g core-js@^3

..then:

npm cache clean -f

..followed by:

npm i

How to Display Multiple Google Maps per page with API V3

Take a Look at this Bundle for Laravel that I Made Recently !


https://github.com/Maghrooni/googlemap

it helps you to create one or multiple maps in your page !

you can find the class on

src/googlemap.php

Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Squaring all elements in a list

import numpy as np
a = [2 ,3, 4]
np.square(a)

Getting HTML elements by their attribute names

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.fn.hasAttribute = function(tagName, attrName){
  var result = [];
  $.each($(tagName), function(index, value) { 
     var attr = $(this).attr(attrName); 
     if (typeof attr !== 'undefined' && attr !== false)
        result.push($(this));
  });
  return result;
}

How can I select from list of values in SQL Server

If it is a list of parameters from existing SQL table, for example ID list from existing Table1, then you can try this:

select distinct ID
      FROM Table1
      where 
      ID in (1, 1, 1, 2, 5, 1, 6)
ORDER BY ID;

Or, if you need List of parameters as a SQL Table constant(variable), try this:

WITH Id_list AS (
     select ID
      FROM Table1
      where 
      ID in (1, 1, 1, 2, 5, 1, 6)
)
SELECT distinct * FROM Id_list
ORDER BY ID;

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.tridenthyundai.ains" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

getch and arrow codes

getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.

For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.

Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.

A handy program to see the action of getch () for various keys is:

#include <stdio.h>
#include <conio.h>

int main ()
{
    int ch;

    while ((ch = _getch()) != 27) /* 27 = Esc key */
    {
        printf("%d", ch);
        if (ch == 0 || ch == 224)
            printf (", %d", _getch ()); 
        printf("\n");
    }

    printf("ESC %d\n", ch);

    return (0);
}

This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.

So, you may do something like:

ch = _getch ();
if (ch == 0 || ch == 224)
{
    switch (_getch ())
    {
        case 72:
            /* Code for up arrow handling */
            break;

        case 80:
            /* Code for down arrow handling */
            break;

        /* ... etc ... */
    }
}

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

The selected answer is clever and tricky. Here's how I did it:

LoginActivity is the root activity of the task, set android:noHistory="true" to it in Manifest.xml; Say you want to logout from SettingsActivity, you can do it as below:

    Intent i = new Intent(SettingsActivity.this, LoginActivity.class);
    i.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

Remove all special characters, punctuation and spaces from string

Use translate:

import string

def clean(instr):
    return instr.translate(None, string.punctuation + ' ')

Caveat: Only works on ascii strings.

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

How to hide a status bar in iOS?

add this key key from dropdownlist in "info.plist" and voila you will no more see top bar that includes elements something like GSM,wifi icon etc.
enter image description here

Jersey Exception : SEVERE: A message body reader for Java class

Q) Code was working fine in Intellj but failing in command line.

Sol) Add dependencies of jersey as a direct dependency rather than a transient one.

Reasoning: Since, it was working fine with IntelliJ, dependencies are correctly configured.

  1. Get required dependencies by one of the following:

    1. check for the IntelliJ running command. Stackoverflow-link
    2. List dependencies from maven mvn dependency:tree
  2. Now, add those problematic jersey dependencies explicitly.

How to display image from URL on Android

You can directly show image from web without downloading it. Please check the below function . It will show the images from the web into your image view.

public static Drawable LoadImageFromWebOperations(String url) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        return null;
    }
}

then set image to imageview using code in your activity.

Suppress warning messages using mysql from within Terminal, but password written in bash script

You can also just redirect the standard error STDERR output to /dev/null

So just do:

mysql -u $user -p$password -e "statement" 2> /dev/null

Android Studio is slow (how to speed up)?

try deleting c:\users\.AndroidStudioX.X folder. it will also remove your android studio settings and customization

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

How to know Hive and Hadoop versions from command prompt?

Below command works , i tried this and got the current version as

/usr/bin/hive --version

How to obtain Telegram chat_id for a specific user?

Whenever user communicate with bot it send information like below:

$response = {
        "update_id":640046715,
        "message":{
            "message_id":1665,
            "from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
            "chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
            "date":1604381276,
            "text":"1"            
            }        
        }

So you can access chat it like:
$update["message"]["chat"]["id"]

Assuming you are using PHP.

Animation CSS3: display + opacity

Based on Michaels answer this is the actual CSS code to use

.parent:hover .child
{
    display: block;

    -webkit-animation: fadeInFromNone 0.5s ease-out;
    -moz-animation: fadeInFromNone 0.5s ease-out;
    -o-animation: fadeInFromNone 0.5s ease-out;
    animation: fadeInFromNone 0.5s ease-out;
}

@-webkit-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@-moz-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@-o-keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

@keyframes fadeInFromNone {
    0% {
        display: none;
        opacity: 0;
    }

    1% {
        display: block;
        opacity: 0;
    }

    100% {
        display: block;
        opacity: 1;
    }
}

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I use both windows and linux, but the solution core.autocrlf true didn't help me. I even got nothing changed after git checkout <filename>.

So I use workaround to substitute git status - gitstatus.sh

#!/bin/bash

git status | grep modified | cut -d' ' -f 4 | while read x; do
 x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
 x2="$(cat $x | md5sum | cut -d' ' -f 1 )"

 if [ "$x1" != "$x2" ]; then
    echo "$x NOT IDENTICAL"
 fi
done

I just compare md5sum of a file and its brother at repository.

Example output:

$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL

Is there a typical state machine implementation pattern?

In my experience using the 'switch' statement is the standard way to handle multiple possible states. Although I am surpirsed that you are passing in a transition value to the per-state processing. I thought the whole point of a state machine was that each state performed a single action. Then the next action/input determines which new state to transition into. So I would have expected each state processing function to immediately perform whatever is fixed for entering state and then afterwards decide if transition is needed to another state.

How to use regex in file find

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

Python Binomial Coefficient

Note that starting Python 3.8, the standard library provides the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

import math
math.comb(10, 5)  # 252
math.comb(10, 10) # 1

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to create exe of a console application

For .net core 2.1 console application, the following approaches worked for me:

1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):

dotnet appName.dll

2 - from Visual Studio

R.C solution and click publish
'Target location' -> 'configure' ->
   'Deployment Mode' = 'Self-Contained'
   'Target Runtime' = 'win-x64 or win-x86 depending on the OS'

References:

For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:

PHP If Statement with Multiple Conditions

I found this method worked for me:

$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
    echo "Product found";
}

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

spacing between form fields

In your CSS file:

input { margin-bottom: 10px; }

Java - checking if parseInt throws exception

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

How do you get the current project directory from C# code when creating a custom MSBuild task?

Try:

var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);

This is solution different from the others does also take into account possible x86 or x64 build.

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

Vuejs: v-model array in multiple input

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value" :key="index">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

Although, I'd try to use something besides an index for the key.

Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/

Visual Studio "Could not copy" .... during build

See this other answer. Basically, you could have MSBuild.exe processes running in the background consuming resource files. If you have any pre or post build tasks that cause an MSBuild to be kicked off via command line, try adding the "/nr:false" flag to this command. But again, see the previous answer for more specific details.

Why can I not create a wheel in python?

Update your pip first:

pip install --upgrade pip

for Python 3:

pip3 install --upgrade pip

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

How to set array length in c# dynamically

Typically, arrays require constants to initialize their size. You could sweep over nvPairs once to get the length, then "dynamically" create an array using a variable for length like this.

InputProperty[] ip = (InputProperty[])Array.CreateInstance(typeof(InputProperty), length);

I wouldn't recommend it, though. Just stick with the

List<InputProperty> ip = ...
...
update.Items = ip.ToArray();

solution. It's not that much less performant, and way better looking.

Is there a better way to refresh WebView?

try this :

mWebView.loadUrl(mWebView.getUrl().toString());

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

How to add conditional attribute in Angular 2?

in angular-2 attribute syntax is

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

so can use like

[attr.role]="myAriaRole ? true: null"

Setting DIV width and height in JavaScript

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>

jQuery/Javascript function to clear all the fields of a form

the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.

$.fn.resetForm = function() {
    return this.each(function(){
        this.reset();
    });
}

Then just call it something like this

$('#divwithformin form').resetForm();

or

$('form').resetForm();

and of course you can still use it in the chain

$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')

Trigger validation of all fields in Angular Form submit

Here is my global function for showing the form error messages.

 function show_validation_erros(form_error_object) {
        angular.forEach(form_error_object, function (objArrayFields, errorName) {
            angular.forEach(objArrayFields, function (objArrayField, key) {
                objArrayField.$setDirty();
            });
        });
    };

And in my any controllers,

if ($scope.form_add_sale.$invalid) { 
    $scope.global.show_validation_erros($scope.form_add_sale.$error);
}

How to perform a real time search and filter on a HTML table

Datatable JS plugin is also one good alternate to accomedate search feature for html table

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
    table.search( this.value ).draw();
} );

https://datatables.net/examples/basic_init/zero_configuration.html

Styling an input type="file" button

Update Nevermind, this doesn't work in IE or it's new brother, FF. Works on every other type of element as expected, but doesn't work on file inputs. A much better way to do this is to just create a file input and a label that links to it. Make the file input display none and boom, it works in IE9+ seamlessly.

Warning: Everything below this is crap!

By using pseudo elements positioned/sized against their container, we can get by with only one input file (no additional markup needed), and style as per usual.

Demo

<input type="file" class="foo">

.foo {
    display: block;
    position: relative;
    width: 300px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.foo:hover:after {
    background: #5978f8;
}
.foo:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #3c5ff4;
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
}

Enjoy guys!

Old Update

Turned this into a Stylus mixin. Should be easy enough for one of you cool SCSS cats to convert it.

file-button(button_width = 150px)
  display block
  position relative
  margin auto
  cursor pointer
  border 0
  height 0
  width 0
  outline none
  &:after
    position absolute
    top 0
    text-align center
    display block
    width button_width
    left -(button_width / 2)

Usage:

<input type="file">

input[type="file"]
    file-button(200px)

How do I rename a local Git branch?

If you want to rename a branch while pointed to any branch, do:

git branch -m <oldname> <newname>

If you want to rename the current branch, you can do:

git branch -m <newname>

A way to remember this is -m is for "move" (or mv), which is how you rename files. Adding an alias could also help. To do so, run the following:

git config --global alias.rename 'branch -m'

If you are on Windows or another case-insensitive filesystem, and there are only capitalization changes in the name, you need to use -M, otherwise, git will throw branch already exists error:

git branch -M <newname>

Function passed as template argument

Template parameters can be either parameterized by type (typename T) or by value (int X).

The "traditional" C++ way of templating a piece of code is to use a functor - that is, the code is in an object, and the object thus gives the code unique type.

When working with traditional functions, this technique doesn't work well, because a change in type doesn't indicate a specific function - rather it specifies only the signature of many possible functions. So:

template<typename OP>
int do_op(int a, int b, OP op)
{
  return op(a,b);
}
int add(int a, int b) { return a + b; }
...

int c = do_op(4,5,add);

Isn't equivalent to the functor case. In this example, do_op is instantiated for all function pointers whose signature is int X (int, int). The compiler would have to be pretty aggressive to fully inline this case. (I wouldn't rule it out though, as compiler optimization has gotten pretty advanced.)

One way to tell that this code doesn't quite do what we want is:

int (* func_ptr)(int, int) = add;
int c = do_op(4,5,func_ptr);

is still legal, and clearly this is not getting inlined. To get full inlining, we need to template by value, so the function is fully available in the template.

typedef int(*binary_int_op)(int, int); // signature for all valid template params
template<binary_int_op op>
int do_op(int a, int b)
{
 return op(a,b);
}
int add(int a, int b) { return a + b; }
...
int c = do_op<add>(4,5);

In this case, each instantiated version of do_op is instantiated with a specific function already available. Thus we expect the code for do_op to look a lot like "return a + b". (Lisp programmers, stop your smirking!)

We can also confirm that this is closer to what we want because this:

int (* func_ptr)(int,int) = add;
int c = do_op<func_ptr>(4,5);

will fail to compile. GCC says: "error: 'func_ptr' cannot appear in a constant-expression. In other words, I can't fully expand do_op because you haven't given me enough info at compiler time to know what our op is.

So if the second example is really fully inlining our op, and the first is not, what good is the template? What is it doing? The answer is: type coercion. This riff on the first example will work:

template<typename OP>
int do_op(int a, int b, OP op) { return op(a,b); }
float fadd(float a, float b) { return a+b; }
...
int c = do_op(4,5,fadd);

That example will work! (I am not suggesting it is good C++ but...) What has happened is do_op has been templated around the signatures of the various functions, and each separate instantiation will write different type coercion code. So the instantiated code for do_op with fadd looks something like:

convert a and b from int to float.
call the function ptr op with float a and float b.
convert the result back to int and return it.

By comparison, our by-value case requires an exact match on the function arguments.

What’s the best way to load a JSONObject from a json text file?

Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

DBCC CHECKIDENT Sets Identity to 0

You are right in what you write in the edit of your question.

After running DBCC CHECKIDENT('TableName', RESEED, 0):
- Newly created tables will start with identity 0
- Existing tables will continue with identity 1

The solution is in the script below, it's sort of a poor-mans-truncate :)

-- Remove all records from the Table
DELETE FROM TableName

-- Use sys.identity_columns to see if there was a last known identity value
-- for the Table. If there was one, the Table is not new and needs a reset
IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'TableName' AND last_value IS NOT NULL) 
    DBCC CHECKIDENT (TableName, RESEED, 0);

Set space between divs

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

How to get current instance name from T-SQL

Just found the answer, in this SO question (literally, inside the question, not any answer):

SELECT @@servername

returns servername\instance as far as this is not the default instance

SELECT @@servicename

returns instance name, even if this is the default (MSSQLSERVER)

any tool for java object to object mapping?

There are some libraries around there:

  • Commons-BeanUtils: ConvertUtils -> Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.

  • Commons-Lang: ArrayUtils -> Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).

  • Spring framework: Spring has an excellent support for PropertyEditors, that can also be used to transform Objects to/from Strings.

  • Dozer: Dozer is a powerful, yet simple Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

  • ModelMapper: ModelMapper is an intelligent object mapping framework that automatically maps objects to each other. It uses a convention based approach to map objects while providing a simple refactoring safe API for handling specific use cases.

  • MapStruct: MapStruct is a compile-time code generator for bean mappings, resulting in fast (no usage of reflection or similar), dependency-less and type-safe mapping code at runtime.

  • Orika: Orika uses byte code generation to create fast mappers with minimal overhead.

  • Selma: Compile-time code-generator for mappings

  • JMapper: Bean mapper generation using Annotation, XML or API (seems dead, last updated 2 years ago)

  • Smooks: The Smooks JavaBean Cartridge allows you to create and populate Java objects from your message data (i.e. bind data to) (suggested by superfilin in comments). (No longer under active development)

  • Commons-Convert: Commons-Convert aims to provide a single library dedicated to the task of converting an object of one type to another. The first stage will focus on Object to String and String to Object conversions. (seems dead, last update 2010)

  • Transmorph: Transmorph is a free java library used to convert a Java object of one type into an object of another type (with another signature, possibly parameterized). (seems dead, last update 2013)

  • EZMorph: EZMorph is simple java library for transforming an Object to another Object. It supports transformations for primitives and Objects, for multidimensional arrays and transformations with DynaBeans (seems dead, last updated 2008)

  • Morph: Morph is a Java framework that eases the internal interoperability of an application. As information flows through an application, it undergoes multiple transformations. Morph provides a standard way to implement these transformations. (seems dead, last update 2008)

  • Lorentz: Lorentz is a generic object-to-object conversion framework. It provides a simple API to convert a Java objects of one type into an object of another type. (seems dead)

  • OTOM: With OTOM, you can copy any data from any object to any other object. The possibilities are endless. Welcome to "Autumn". (seems dead)

How can git be installed on CENTOS 5.5?

yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel gcc
wget http://git-core.googlecode.com/files/git-1.7.11.4.tar.gz
tar zxvf git-1.7.11.4.tar.gz 
cd git-1.7.11.4
./configure 
make
make install

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

Watch multiple $scope attributes

Angular introduced $watchGroup in version 1.3 using which we can watch multiple variables, with a single $watchGroup block $watchGroup takes array as first parameter in which we can include all of our variables to watch.

$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
   console.log("new value of var1 = " newVals[0]);
   console.log("new value of var2 = " newVals[1]);
   console.log("old value of var1 = " oldVals[0]);
   console.log("old value of var2 = " oldVals[1]);
});