Programs & Examples On #Passive sts

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

VSCode regex find & replace submatch math?

Given a regular expression of (foobar) you can reference the first group using $1 and so on if you have more groups in the replace input field.

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

WAMP/XAMPP is responding very slow over localhost

I run on wamp and I had this problem once. There can be many factors to this though there is 5 main ones that come to my mind.

1st. A program can cause this(Even antivirus software just depends what you have.)

2nd. Is your computer full or using alot of space this happen to a partner site of mine.

3rd. Check your regerstry files there could be errors or other things. (This end up being my problem.)

4th. After you uninstalled it did you manually delete the files that were left on your computer.(Yes even after you uninstall with wamp it has a tendency to leave a folder or 2 with some important data on it. When you install this will not be remodified and will stay the same.)

5th. Download the latest wamp or the lastest stable version of it.

Hope one of these things help.

Installing Homebrew on OS X

Not sure why nobody mentioned this : when you run the installation command from the official site, in the final lines you would see something like below, and you need to follow the ==> Next steps:

==> Installation successful!

==> Homebrew has enabled anonymous aggregate formulae and cask analytics.
Read the analytics documentation (and how to opt-out) here:
  https://docs.brew.sh/Analytics
No analytics data has been sent yet (or will be during this `install` run).

==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
  https://github.com/Homebrew/brew#donations

==> Next steps:
- Add Homebrew to your PATH in /Users/{YOUR USER NAME}/.bash_profile:
    echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users/{YOUR USER NAME}/.bash_profile
    eval $(/opt/homebrew/bin/brew shellenv)

This is for bash shell. You will see different steps for every different shell, but the source of the steps are same.

Why are my PHP files showing as plain text?

Are you using the userdir mod?

In that case the thing is that PHP5 seems to be disabling running scripts from that location by default and you have to comment out the following lines:

<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

in /etc/apache2/mods-enabled/php5.conf (on a ubuntu system)

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

How to determine whether a given Linux is 32 bit or 64 bit?

With respect to the answer "getconf LONG_BIT".

I wrote a simple function to do it in 'C':

/*
 * check_os_64bit
 *
 * Returns integer:
 *   1 = it is a 64-bit OS
 *   0 = it is NOT a 64-bit OS (probably 32-bit)
 *   < 0 = failure
 *     -1 = popen failed
 *     -2 = fgets failed
 *
 * **WARNING**
 * Be CAREFUL! Just testing for a boolean return may not cut it
 * with this (trivial) implementation! (Think of when it fails,
 * returning -ve; this could be seen as non-zero & therefore true!)
 * Suggestions?
 */
static int check_os_64bit(void)
{
    FILE *fp=NULL;
    char cb64[3];

    fp = popen ("getconf LONG_BIT", "r");
    if (!fp)
       return -1;

    if (!fgets(cb64, 3, fp))
        return -2;

    if (!strncmp (cb64, "64", 3)) {
        return 1;
    }
    else {
        return 0;
    }
}

Good idea, the 'getconf'!

How to split the screen with two equal LinearLayouts?

I am answering this question after 4-5 years but best practices to do this as below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <LinearLayout
      android:id="@+id/firstLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toLeftOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>

   <View
      android:id="@+id/secondView"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_centerHorizontal="true" />

   <LinearLayout
      android:id="@+id/thirdLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toRightOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>
</RelativeLayout>

This is right approach as use of layout_weight is always heavy for UI operations. Splitting Layout equally using LinearLayout is not good practice

When adding a Javascript library, Chrome complains about a missing source map, why?

This worked for me

Deactivate AdBlock.

Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.

Refresh.

How may I sort a list alphabetically using jQuery?

Put the list in an array, use JavaScript's .sort(), which is by default alphabetical, then convert the array back to a list.

http://www.w3schools.com/jsref/jsref_sort.asp

Give all permissions to a user on a PostgreSQL database

GRANT USAGE ON SCHEMA schema_name TO user;

pass JSON to HTTP POST Request

I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js

Which uses the following format:

request({
    url: url,
    method: "POST",
    headers: {
        "content-type": "application/json",
        },
    json: requestData
//  body: JSON.stringify(requestData)
    }, function (error, resp, body) { ...

How to run script as another user without password?

try running:

su -c "Your command right here" -s /bin/sh username

This will run the command as username given that you have permissions to sudo as that user.

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

Operation must use an updatable query. (Error 3073) Microsoft Access

MS Access - joining tables in an update query... how to make it updatable

  1. Open the query in design view
  2. Click once on the link b/w tables/view
  3. In the “properties” window, change the value for “unique records” to “yes”
  4. Save the query as an update query and run it.

Command to get time in milliseconds

The other answers are probably sufficient in most cases but I thought I'd add my two cents as I ran into a problem on a BusyBox system.

The system in question did not support the %N format option and doesn't have no Python or Perl interpreter.

After much head scratching, we (thanks Dave!) came up with this:

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

It extracts the seconds and microseconds from the output of adjtimex (normally used to set options for the system clock) and prints them without new lines (so they get glued together). Note that the microseconds field has to be pre-padded with zeros, but this doesn't affect the seconds field which is longer than six digits anyway. From this it should be trivial to convert microseconds to milliseconds.

If you need a trailing new line (maybe because it looks better) then try

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }' && printf "\n"

Also note that this requires adjtimex and awk to be available. If not then with BusyBox you can point to them locally with:

ln -s /bin/busybox ./adjtimex
ln -s /bin/busybox ./awk

And then call the above as

./adjtimex | ./awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

Or of course you could put them in your PATH

EDIT:

The above worked on my BusyBox device. On Ubuntu I tried the same thing and realised that adjtimex has different versions. On Ubuntu this worked to output the time in seconds with decimal places to microseconds (including a trailing new line)

sudo apt-get install adjtimex
adjtimex -p | awk '/raw time:/ { print $6 }'

I wouldn't do this on Ubuntu though. I would use date +%s%N

When and why do I need to use cin.ignore() in C++?

Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin.ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

Comparing two .jar files

  1. Rename .jar to .zip
  2. Extract
  3. Decompile class files with jad
  4. Recursive diff

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

And just in case someone here is also not paying attention (like me):

For Microsoft SQL Server 2012, in the options dialogue box, there is a sneaky little check box that APPARENTLY hides all other setting. Although I got to say that I have missed that little monster all this time!!!

After that, you may proceed with the steps, designer, uncheck prevent saving blah blah blah...

sneaky_check_box_in_option

Python, Unicode, and the Windows console

Python 3.6 windows7: There is several way to launch a python you could use the python console (which has a python logo on it) or the windows console (it's written cmd.exe on it).

I could not print utf8 characters in the windows console. Printing utf-8 characters throw me this error:

OSError: [winError 87] The paraneter is incorrect 
Exception ignored in: (_io-TextIOwrapper name='(stdout)' mode='w' ' encoding='utf8') 
OSError: [WinError 87] The parameter is incorrect 

After trying and failing to understand the answer above I discovered it was only a setting problem. Right click on the top of the cmd console windows, on the tab font chose lucida console.

Zoom in on a point (using scale and translate)

if(wheel > 0) {
    this.scale *= 1.1; 
    this.offsetX -= (mouseX - this.offsetX) * (1.1 - 1);
    this.offsetY -= (mouseY - this.offsetY) * (1.1 - 1);
}
else {
    this.scale *= 1/1.1; 
    this.offsetX -= (mouseX - this.offsetX) * (1/1.1 - 1);
    this.offsetY -= (mouseY - this.offsetY) * (1/1.1 - 1);
}

How can I render a list select box (dropdown) with bootstrap?

Skelly's nice and easy answer is now outdated with the changes to the dropdown syntax in Bootstap. Instead use this:

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.form-group').find('button[data-toggle="dropdown"]').html(selText+' <span class="caret"></span>');
});

How to make a div center align in HTML

how about something along these lines

<style type="text/css">
  #container {
    margin: 0 auto;
    text-align: center; /* for IE */
  }

  #yourdiv {
    width: 400px;
    border: 1px solid #000;
  }
</style>

....

<div id="container">
  <div id="yourdiv">
    weee
  </div>
</div>

How to check if object has any properties in JavaScript?

Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

var ad = {}; 
Object.keys(ad).length;//this will be 0 in this case

Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

how to check the jdk version used to compile a .class file

You can try jclasslib:

https://github.com/ingokegel/jclasslib

It's nice that it can associate itself with *.class extension.

Input mask for numeric and decimal

If your system is in English, use @Rick answer:

If your system is in Brazilian Portuguese, use this:

Import:

<script
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script     src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>

HTML:

<input class="mask" type="text" />

JS:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});

Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.

It is it, I hope that it help someone. I spend a lot of time to understand it.

How can I change the default width of a Twitter Bootstrap modal box?

Add the following on your css file

.popover{
         width:auto !important; 
         max-width:445px !important; 
         min-width:200px !important;
       }

Auto-increment primary key in SQL tables

for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:

tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK

and try to save as it should work now

How can I get query string values in JavaScript?

Keep it simple in plain JavaScript code:

function qs(key) {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars[key];
}

Call it from anywhere in the JavaScript code:

var result = qs('someKey');

Row count with PDO

For straight queries where I want a specific row, and want to know if it was found, I use something like:

function fetchSpecificRow(&$myRecord) {
    $myRecord = array();
    $myQuery = "some sql...";
    $stmt = $this->prepare($myQuery);
    $stmt->execute(array($parm1, $parm2, ...));
    if ($myRecord = $stmt->fetch(PDO::FETCH_ASSOC)) return 0;
    return $myErrNum;
}

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.

UIWebView open links in Safari

Add this to the UIWebView delegate:

(edited to check for navigation type. you could also pass through file:// requests which would be relative links)

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }

    return YES;
}

Swift Version:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(request.URL!)
            return false
        }
        return true
    }

Swift 3 version:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.linkClicked {
        UIApplication.shared.openURL(request.url!)
        return false
    }
    return true
}

Swift 4 version:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    guard let url = request.url, navigationType == .linkClicked else { return true }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    return false
}

Update

As openURL has been deprecated in iOS 10:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
            UIApplication *application = [UIApplication sharedApplication];
            [application openURL:[request URL] options:@{} completionHandler:nil];
            return NO;
        }

        return YES;
}

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    },
    crossDomain: true
});

Reverse engineering from an APK file to a project

Another tool that you may want to use is APK Studio It relies howewer on third party tools: Apktool, jadx, ADB and Uber APK signer that you need to download separately.

How to bind inverse boolean properties in WPF?

I wanted my XAML to remain as elegant as possible so I created a class to wrap the bool which resides in one of my shared libraries, the implicit operators allow the class to be used as a bool in code-behind seamlessly

public class InvertableBool
{
    private bool value = false;

    public bool Value { get { return value; } }
    public bool Invert { get { return !value; } }

    public InvertableBool(bool b)
    {
        value = b;
    }

    public static implicit operator InvertableBool(bool b)
    {
        return new InvertableBool(b);
    }

    public static implicit operator bool(InvertableBool b)
    {
        return b.value;
    }

}

The only changes needed to your project are to make the property you want to invert return this instead of bool

    public InvertableBool IsActive 
    { 
        get 
        { 
            return true; 
        } 
    }

And in the XAML postfix the binding with either Value or Invert

IsEnabled="{Binding IsActive.Value}"

IsEnabled="{Binding IsActive.Invert}"

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Although this an old post, I am sharing another working example.

"COLUMN COUNT AS WELL AS EACH COLUMN DATATYPE MUST MATCH WHEN 'UNION' OR 'UNION ALL' IS USED"

Let us take an example:

1:

In SQL if we write - SELECT 'column1', 'column2' (NOTE: remember to specify names in quotes) In a result set, it will display empty columns with two headers - column1 and column2

2: I share one simple instance I came across.

I had seven columns with few different datatypes in SQL. I.e. uniqueidentifier, datetime, nvarchar

My task was to retrieve comma separated result set with column header. So that when I export the data to CSV I have comma separated rows with first row as header and has respective column names.

SELECT CONVERT(NVARCHAR(36), 'Event ID') + ', ' + 
'Last Name' + ', ' + 
'First Name' + ', ' + 
'Middle Name' + ', ' + 
CONVERT(NVARCHAR(36), 'Document Type') + ', ' + 
'Event Type' + ', ' + 
CONVERT(VARCHAR(23), 'Last Updated', 126)

UNION ALL

SELECT CONVERT(NVARCHAR(36), inspectionid) + ', ' + 
       individuallastname + ', ' + 
       individualfirstname + ', ' + 
       individualmiddlename + ', ' +
       CONVERT(NVARCHAR(36), documenttype) + ', ' + 
       'I' + ', ' +
       CONVERT(VARCHAR(23), modifiedon, 126)
FROM Inspection

Above, columns 'inspectionid' & 'documenttype' has uniqueidentifer datatype and so applied CONVERT(NVARCHAR(36)). column 'modifiedon' is datetime and so applied CONVERT(NVARCHAR(23), 'modifiedon', 126).

Parallel to above 2nd SELECT query matched 1st SELECT query as per datatype of each column.

How to apply shell command to each line of a command output?

i like to use gawk for running multiple commands on a list, for instance

ls -l | gawk '{system("/path/to/cmd.sh "$1)}'

however the escaping of the escapable characters can get a little hairy.

How to override application.properties during production in Spring-Boot?

The spring configuration precedence is as follows.

  1. ServletConfig init Parameter
  2. ServletContext init parameter
  3. JNDI attributes
  4. System.getProperties()

So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Yes. They are different file formats (and their file extensions).

Wikipedia entries for each of the formats will give you quite a bit of information:

  • JPEG (or JPG, for the file extension; Joint Photographic Experts Group)
  • PNG (Portable Network Graphics)
  • BMP (Bitmap)
  • GIF (Graphics Interchange Format)
  • TIFF (or TIF, for the file extension; Tagged Image File Format)

Image formats can be separated into three broad categories:

  • lossy compression,
  • lossless compression,
  • uncompressed,

Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.

Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.

Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)

TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.

When to use a certain image compression format really depends on what is being compressed.

Related question: Ruthlessly compressing large images for the web

Bootstrap 3 with remote Modal

I do it this way:

<!-- global template loaded in all pages // -->
     <div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="newsLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h3 class="newsLabel"></h3>
                    </div>
                    <div class="modal-body">
                            <div class="loading">
                                <span class="caption">Loading...</span>
                               <img src="/images/loading.gif" alt="loading">
                        </div>
                    </div>
                    <div class="modal-footer caption">
                        <button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

Here is my a href:

<a href="#NewsModal" onclick="remote=\'modal_newsfeed.php?USER='.trim($USER).'&FUNCTION='.trim(urlencode($FUNCTIONCODE)).'&PATH_INSTANCE='.$PATH_INSTANCE.'&ALL=ALL\'
                                        remote_target=\'#NewsModal .modal-body\'" role="button" data-toggle="modal">See All Notifications <i class="m-icon-swapright m-icon-dark"></i></a>

What is your favorite C programming trick?

Using the otherwise pointless ? : operator to initialise a const variable

const int bytesPerPixel = isAlpha() ? 4 : 3;

How can I execute Shell script in Jenkinsfile?

If you see your error message it says

Building in workspace /var/lib/jenkins/workspace/AutoScript

and as per your comments you have put urltest.sh in

/var/lib/jenkins

Hence Jenkins is not able to find the file. In your build step do this thing, it will work

cd             # which will point to /var/lib/jenkins
./urltest.sh   # it will run your script

If it still fails try to chown the file as jenkin user may not have file permission, but I think if you do above step you will be able to run.

jquery find closest previous sibling with class

Try:

$('li.current_sub').prevAll("li.par_cat:first");

Tested it with your markup:

$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");

will fill up the closest previous li.par_cat with "woohoo".

What does "dereferencing" a pointer mean?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

int a = 10;
int* ptr = &a;

printf("%d", *ptr); // With *ptr I'm dereferencing the pointer. 
                    // Which means, I am asking the value pointed at by the pointer.
                    // ptr is pointing to the location in memory of the variable a.
                    // In a's location, we have 10. So, dereferencing gives this value.

// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.

 *ptr = 20;         // Now a's content is no longer 10, and has been modified to 20.

Forking vs. Branching in GitHub

Here are the high-level differences:

Forking

Pros

  • Keeps branches separated by user
  • Reduces clutter in the primary repository
  • Your team process reflects the external contributor process

Cons

  • Makes it more difficult to see all of the branches that are active (or inactive, for that matter)
  • Collaborating on a branch is trickier (the fork owner needs to add the person as a collaborator)
  • You need to understand the concept of multiple remotes in Git
    • Requires additional mental bookkeeping
    • This will make the workflow more difficult for people who aren't super comfortable with Git

Branching

Pros

  • Keeps all of the work being done around a project in one place
  • All collaborators can push to the same branch to collaborate on it
  • There's only one Git remote to deal with

Cons

  • Branches that get abandoned can pile up more easily
  • Your team contribution process doesn't match the external contributor process
  • You need to add team members as contributors before they can branch

SQL Server Configuration Manager not found

From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

This has been the most annoying thing to deal with. In hopes of saving your time.

IF go was installed as root user. The root user of your system's bash_profile text file ~/.bash_profile needs to have $GOROOT assigned to the go install directory and $GOPATH needs to be assigned to go /src directory.

  ...$# sudo su
  ...$# vi ~/.bash_profile

    ***Story continues in vi editor***

    GOROOT=$GOROOT:/usr/local/go
    GOPATH=$GOPATH:/usr/local/go/src
    ...
    [your regular PATH stuff here]
    ...

be sure the path to go binary is in your path on .bash_profile

PATH=$PATH:$HOME/bin:/usr/local/bin:/usr/local/go/bin

This PATH can be as long a string it needs to be..to add new items just separate by colon :

exit vi editor and saving bash profile (:wq stands for write and quit)

  [esc] 
  [shift] + [:] 
  :wq

You have to log out of terminal and log back in for profile to initiate again..or you can just kick start it by using export.

...$# export GOPATH=/usr/local/go/src

You can verify go env:

...$# go env

Yay!

GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/usr/local/go/src"
GORACE=""
GOROOT="/usr/local/go"

Now you can sudo and go will be able to download and create directories inside go/src and you can get down to what you were trying to get done.

example

# sudo go get github.com/..

Now you will run into another problem..you might not have git installed..that's another adventure..:)

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

PHPUnit assert that an exception was thrown?

Here's all the exception assertions you can do. Note that all of them are optional.

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        // make your exception assertions
        $this->expectException(InvalidArgumentException::class);
        // if you use namespaces:
        // $this->expectException('\Namespace\MyExceptio??n');
        $this->expectExceptionMessage('message');
        $this->expectExceptionMessageRegExp('/essage$/');
        $this->expectExceptionCode(123);
        // code that throws an exception
        throw new InvalidArgumentException('message', 123);
   }

   public function testAnotherException()
   {
        // repeat as needed
        $this->expectException(Exception::class);
        throw new Exception('Oh no!');
    }
}

Documentation can be found here.

Adding n hours to a date in Java?

If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:

import java.time.Duration;
import java.time.LocalDateTime;

...

LocalDateTime yourDate = ...

...

// Adds 1 hour to your date.

yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
// OR
yourDate = yourDate + Duration.parse("PT1H"); // Groovy.  

How to add bootstrap to an angular-cli project

Run This Command

npm install bootstrap@3

your Angular.json

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],

How to check ASP.NET Version loaded on a system?

You can see which version gets executed when you load the page with Google Chrome + developer tools (preinstalled) or Firefox + Firebug (add-on).

I use Google Chrome:

  1. Open Chrome and use Ctrl+Shift+I to open the developer tools.
  2. Go to the "Network" Tab
  3. Click on the small button at the bottom "Preserve log upon Navigation"
  4. Load any of your pages
  5. Click on the response header

It looks like this:

enter image description here

How to change the color of a CheckBox?

If textColorSecondary does not work for you, you might have defined colorControlNormal in your theme to be a different color. If so, just use

<style name="yourStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">your_color</item> <!-- for checked state -->
    <item name="colorControlNormal">your color</item> <!-- for unchecked state -->
</style>

How to get the full url in Express?

Thank you all for this information. This is incredibly annoying.

Add this to your code and you'll never have to think about it again:

var app = express();

app.all("*", function (req, res, next) {  // runs on ALL requests
    req.fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
        next()
})

You can do or set other things there as well, such as log to console.

dyld: Library not loaded ... Reason: Image not found

I got this error after using asdf to switch my python version. When you activate the virtualenv it gets confused.

Instead recreate the virtualenv like so

$ rm -rf venv
$ python -m venv venv

This time when you activate the virtualenv it will find the correct python.

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

How to exclude a directory from ant fileset, based on directories contents

it works for me with a jar target:

<jar jarfile="${server.jar}" basedir="${classes.dir}" excludes="**/client/">
  <manifest>
    <attribute name="Main-Class" value="${mainServer.class}" />
  </manifest>
</jar>

this code include all files in "classes.dir" but exclude the directory "client" from the jar.

gcc-arm-linux-gnueabi command not found

if you are on 64 bit os then you need to install this additional libraries.

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0

How to copy marked text in notepad++

No, as of Notepad++ 5.6.2, this doesn't seem to be possible. Although column selection (Alt+Selection) is possible, multiple selections are obviously not implemented and thus also not supported by the search function.

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

CSS Circular Cropping of Rectangle Image

Try this:

img {
    height: auto;
    width: 100%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
}

DEMO here.

OR:

.rounded {
    height: 100px;
    width: 100px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
    background:url("http://www.electricvelocity.com.au/Upload/Blogs/smart-e-bike-side_2.jpg") center no-repeat;
    background-size:cover;
}

DEMO here.

Converting NSString to NSDate (and back again)

Date to NSString

NSString *dateString = [NSString stringWithFormat:@"%@",[NSDate date]];
NSLog(@"string: %@",dateString ); //2015-03-24 12:28:49 +0000

NSString to NSDate

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date); //015-03-24 12:28:49 +0000

How do I get the parent directory in Python?

If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:

os.path.split(os.path.dirname(currentDir))[1]

i.e. with a currentDir value of /home/user/path/to/myfile/file.ext

The above command will return:

myfile

how to increase java heap memory permanently?

You also use this below to expand the memory

export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"

Xmx specifies the maximum memory allocation pool for a Java virtual machine (JVM)

Xms specifies the initial memory allocation pool.

Xss setting memory size of thread stack

XX:MaxPermSize: the maximum permanent generation size

SQL SELECT from multiple tables

SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`

HashMaps and Null values?

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

To solve the issue try to repair the .net framework 4 and then run the command

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

enter image description here

Find JavaScript function definition in Chrome

You can print the function by evaluating the name of it in the console, like so

> unknownFunc
function unknownFunc(unknown) {
    alert('unknown seems to be ' + unknown);
}

this won't work for built-in functions, they will only display [native code] instead of the source code.

EDIT: this implies that the function has been defined within the current scope.

How to write multiple conditions in Makefile.am with "else if"

ifdef $(HAVE_CLIENT)
libtest_LIBS = \
    $(top_builddir)/libclient.la
else
ifdef $(HAVE_SERVER)
libtest_LIBS = \
    $(top_builddir)/libserver.la
else
libtest_LIBS = 
endif
endif

NOTE: DO NOT indent the if then it don't work!

horizontal scrollbar on top and bottom of table

As far as I'm aware this isn't possible with HTML and CSS.

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

What's the difference between ".equals" and "=="?

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Even though the strings have the same exact characters (“xyz”), The code above will actually output: obj1==obj2 is FALSE

Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

This code will output the following:

obj1==obj2 is TRUE

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

go to link on button click - jquery

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

Place a button right aligned

a modern approach in 2019 using flex-box

with div tag

_x000D_
_x000D_
<div style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
    <input type="button" value="Click Me"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

with span tag

_x000D_
_x000D_
<span style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
    <input type="button" value="Click Me"/>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Express-js can't GET my static files, why?

if your setup

myApp
  |
  |__ public
  |     |
  |     |__  stylesheets
  |     |     |
  |     |     |__ style.css
  |     |
  |     |___ img
  |           |
  |           |__ logo.png
  |
  |__ app.js

then,
put in app.js

app.use('/static', express.static('public'));

and refer to your style.css: (in some .pug file):

link(rel='stylesheet', href='/static/stylesheets/style.css')

Getting an attribute value in xml element

I think I got it. I have to use org.w3c.dom.Element explicitly. I had a different Element field too.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

How to execute a program or call a system command from Python

import os
os.system("your command")

Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant documentation on the 'os' and 'sys' modules. There are a bunch of functions (exec* and spawn*) that will do similar things.

Amazon AWS Filezilla transfer permission denied

if you are using centOs then use

sudo chown -R centos:centos /var/www/html

sudo chmod -R 755 /var/www/html

For Ubuntu

sudo chown -R ubuntu:ubuntu /var/www/html

sudo chmod -R 755 /var/www/html

For Amazon ami

sudo chown -R ec2-user:ec2-user /var/www/html

sudo chmod -R 755 /var/www/html

Copy table to a different database on a different SQL Server

Yes. add a linked server entry, and use select into using the four part db object naming convention.

Example:

SELECT * INTO targetTable 
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]

CSS: Hover one element, effect for multiple elements?

I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:

<html>
<head>
<style>
  div.both:hover .image { border: 1px solid blue }
  div.both:hover .layer { border: 1px solid blue }
</style>
</head>

<body>
<div class="section">

<div class="both">
  <div class="image"><img src="myImage.jpg" /></div>
  <div class="layer">Lorem Ipsum</div>
</div>

</div>
</body>
</html>

ModuleNotFoundError: What does it mean __main__ is not a package?

Just use the name of the main folder which the .py file is in.

from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after

In JPA 2, using a CriteriaQuery, how to count results

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.select(cb.count(cq.from(MyEntity.class)));

return em.createQuery(cq).getSingleResult();

Generate pdf from HTML in div using Javascript

This example works great.

<button onclick="genPDF()">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
    function genPDF() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');
    
        doc.save('Test.pdf');
    }
</script>

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

What does "./" (dot slash) refer to in terms of an HTML file path location?

. is a shorthand for the current directory and is used in Linux and Unix to execute a compiled program in the current directory. That is why you don't see this used in Web Development much except by open source, non-Windows frameworks like Google Angular which was written by people stuck on open source platforms.

./ also resolves to the current directory and is atypical in Web but supported as a path in some open source frameworks. Because it resolves the same as no path to the current file directory its not used. Example: ./image.jpg = image.jpg. Again, this is a relic of Unix operating systems that need path resolutions like this to run executables and resolve paths for security reasons. Its not a typical web path. That is why this syntax is redundant.

../ is a traditional web path that goes one directory up

/ is the ROOT of your website

These path resolutions below are true...

./folder= folder this is always true in web path resolution

./file.html = file.html this is always true in web path resolution

./ = {no path} an empty path is the same as ./ in the web world

{no path} = / an empty path is the same as the web root if your file is in the root directory

./ = / ONLY if you are in the root folder

../ = / ONLY if you are one folder below the web root

How to update maven repository in Eclipse?

Right-click on your project and choose Maven > Update Snapshots. In addition to that you can set "update Maven projects on startup" in Window > Preferences > Maven

UPDATE: In latest versions of Eclipse: Maven > Update Project. Make sure "Force Update of Snapshots/Releases" is checked.

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Remove a character at a certain position in a string - javascript

you can use substring() method. ex,

var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

How to select the first, second, or third element with a given class name?

Yes, you can do this. For example, to style the td tags that make up the different columns of a table you could do something like this:

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results

enter image description here

DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size

Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)

DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit

Check for special characters in string

Check if a string contains at least one password special character:

For reference: ASCII Table -- Printable Characters

Special character ranges in the ASCII table are:

  • Space to /
  • : to @
  • [ to `
  • { to ~

Therefore, use this:

/[ -/:-@[-`{-~]/.test(string)

How to set margin of ImageView using code, not xml

sample code is here ,its very easy

LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                params1.height = 70;
                params1.setMargins(0, 210, 0, 0);//top margin -210 here
                twoLetter.setLayoutParams(params1);//setting layout params
                twoLetter.setImageResource(R.drawable.oo);

show and hide divs based on radio button click

You're on the right track, but you forgot two things:

  1. add the desc classes to your description divs
  2. You have numeric values for the input but text for the id.

I have fixed the above and also added a line to initially hide() the third description div.

Check it out in action - http://jsfiddle.net/VgAgu/3/

HTML

<div id="myRadioGroup">
    2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
    3 Cars<input type="radio" name="cars" value="3" />

    <div id="Cars2" class="desc">
        2 Cars Selected
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        3 Cars
    </div>
</div>

JQuery

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

Javascript : get <img> src and set as variable?

Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>

Adding new line of data to TextBox

Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.

Alert after page load

Another option is to use the defer attribute on the script, but it's only appropriate for external scripts with a src attribute:

<script src = "exampleJsFile.js" defer> </script>

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:

from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse

A =  np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)

similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))

#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))

Results:

pairwise dense output:
[[ 1.          0.40824829  0.40824829]
[ 0.40824829  1.          0.33333333]
[ 0.40824829  0.33333333  1.        ]]

pairwise sparse output:
(0, 1)  0.408248290464
(0, 2)  0.408248290464
(0, 0)  1.0
(1, 0)  0.408248290464
(1, 2)  0.333333333333
(1, 1)  1.0
(2, 1)  0.333333333333
(2, 0)  0.408248290464
(2, 2)  1.0

If you want column-wise cosine similarities simply transpose your input matrix beforehand:

A_sparse.transpose()

How do I find all files containing specific text on Linux?

Use:

grep -Erni + "text you wanna search"

The command will search recursively in all files and directories of the current directory and print the result.

Note: if your grep output isn't colored, you can change it by using the grep='grep --color=always' alias in your shell source file.

Warning: comparison with string literals results in unspecified behaviour

You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp().

If you want to compare a character you need to compare to a character, not a string. "a" is the string a, which occupies two bytes (the a and the terminating null byte), while the character a is represented by 'a' in C.

Escaping special characters in Java Regular Expressions

use

pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();

will give result as yourcontent as is

What does the @ symbol before a variable name mean in C#?

The @ symbol serves 2 purposes in C#:

Firstly, it allows you to use a reserved keyword as a variable like this:

int @int = 15;

The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:

var myString = "c:\\myfolder\\myfile.txt"

alternatively you can do this:

var myString = @"c:\myFolder\myfile.txt"

Angular2 set value for formGroup

For set value when your control is FormGroup can use this example

this.clientForm.controls['location'].setValue({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    });

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

How can I set the initial value of Select2 when using AJAX?

It's works for me ...

Don't use jQuery, only HTML: Create the option value you will display as selected. If ID it's in select2 data it will selected automatically.

<select id="select2" name="mySelect2">
  <option value="mySelectedValue">
        Hello, I'm here!
  </option>
</select>

Select2.org - Default Pre Selected values

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

Log4net rolling daily filename with date in the file name

I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'

            log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            Hierarchy hierarchy = (Hierarchy)repository;
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = "Log_";
            roller.DatePattern = "MM-dd-yyyy'.log'";
            roller.Layout = patternLayout;
            roller.MaxFileSize = 1024*1024*10;
            roller.MaxSizeRollBackups = 10;
            roller.StaticLogFileName = false;
            roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to create war files

Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.

(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)

jar -cvf projectname.war *

Reference Link

Counting the number of occurences of characters in a string

Try this:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}

Get paragraph text inside an element

change your html to the following:

<ul>
    <li onclick="myfunction()">
        <span></span>
        <p id="myParagraph">This Text</p>
    </li>
</ul>

then you can get the content of your paragraph with the following function:

function getContent() {
    return document.getElementById("myParagraph").innerHTML;
}

CSS text-overflow in a table cell?

If you just want the table to auto-layout

Without using max-width, or percentage column widths, or table-layout: fixed etc.

https://jsfiddle.net/tturadqq/

How it works:


Step 1: Just let the table auto-layout do its thing.

When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:

enter image description here


Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em

(the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')

enter image description here


Step 3: Set title on the divs

This is good for accessibility, and is necessary for the little trick we'll use in a moment.

enter image description here


Step 4: Add a CSS ::after on the div

This is the tricky bit. We set a CSS ::after, with content: attr(title), then position that on top of the div and set text-overflow: ellipsis. I've coloured it red here to make it clear.

(Note how the long column now has a tailing ellipsis)

enter image description here


Step 5: Set the colour of the div text to transparent

And we're done!

enter image description here

Programmatically open new pages on Tabs

You can't directly control this, because it's an option controlled by Internet Explorer users.

Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.

Why do python lists have pop() but not push()

Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.

Think of a queue vs. a stack.

http://docs.python.org/tutorial/datastructures.html

Edit: To reword my second sentence more exactly, "Appending" very clearly implies adding something to the end of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

java- reset list iterator to first element of the list

Calling iterator() on a Collection impl, probably would get a new Iterator on each call.

Thus, you can simply call iterator() again to get a new one.


Code

IteratorLearn.java

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * Iterator learn.
 *
 * @author eric
 * @date 12/30/18 4:03 PM
 */
public class IteratorLearn {
    @Test
    public void test() {
        Collection<Integer> c = new HashSet<>();
        for (int i = 0; i < 10; i++) {
            c.add(i);
        }

        Iterator it;

        // iterate,
        it = c.iterator();
        System.out.println("\niterate:");
        while (it.hasNext()) {
            System.out.printf("\t%d\n", it.next());
        }
        Assert.assertFalse(it.hasNext());

        // consume,
        it = c.iterator();
        System.out.println("\nconsume elements:");
        it.forEachRemaining(ele -> System.out.printf("\t%d\n", ele));
        Assert.assertFalse(it.hasNext());
    }
}

Output:

iterate:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

consume elements:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

Prevent HTML5 video from being downloaded (right-click saved)?

As a client-side developer I recommend to use blob URL, blob URL is a client-side URL which refers to a binary object

<video id="id" width="320" height="240"  type='video/mp4' controls  > </video>

in HTML leave your video src blank, and in JS fetch the video file using AJAX, make sure the response type is blob

window.onload = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'mov_bbb.mp4', true);
    xhr.responseType = 'blob'; //important
    xhr.onload = function(e) {
        if (this.status == 200) {
            console.log("loaded");
            var blob = this.response;
            var video = document.getElementById('id');
            video.oncanplaythrough = function() {
                console.log("Can play through video without stopping");
                URL.revokeObjectURL(this.src);
            };
            video.src = URL.createObjectURL(blob);
            video.load();
        }
    };
    xhr.send();
}

Note: This method is not recommended for large file

EDIT

  • Use cross-origin blocking for avoiding direct downloading

  • if the video is delivered by an API Use different method (PUT/POST) instead of 'GET'

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Find and replace strings in vim on multiple lines

The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

:6,10s/<search_string>/<replace_string>/g | 14,18&&

If you have many ranges though, I'd rather use a loop:

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor

How to remove an unpushed outgoing commit in Visual Studio?

Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made. In order to reset before a given commit you thus have to select its parent.

Depending on what you want to do with the changes choose hard, which will get rid of them locally. Or choose soft which will undo the commit but will leave your working directory with the changes in your discarded commit.

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

How to set cache: false in jQuery.get call

Set cache: false in jQuery.get call using Below Method

use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.

Or

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

Javascript how to parse JSON array

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

Selenium using Python - Geckodriver executable needs to be in PATH

To add my two cents, it is also possible to do echo PATH (Linux) and just move geckodriver to the folder of your liking. If a system (not virtual environment) folder is the target, the driver becomes globally accessible.

Is JavaScript's "new" keyword considered harmful?

I have just read some parts of his Crockfords book "Javascript: The Good Parts". I get the feeling that he considers everything that ever has bitten him as harmful:

About switch fall through:

I never allow switch cases to fall through to the next case. I once found a bug in my code caused by an unintended fall through immediately after having made a vigorous speech about why fall through was sometimes useful. (page 97, ISBN 978-0-596-51774-8)

About ++ and --

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging exessive trickiness. They are second only to faulty architecture in enabling viruses and other security menaces. (page 122)

About new:

If you forget to include the new prefix when calling a constructor function, then this will not be bound to the new object. Sadly, this will be bound to the global object, so instead of augmenting your new object, you will be clobbering global variables. That is really bad. There is no compile warning, and there is no runtime warning. (page 49)

There are more, but I hope you get the picture.

My answer to your question: No, it's not harmful. but if you forget to use it when you should you could have some problems. If you are developing in a good environment you notice that.

Update

About a year after this answer was written the 5th edition of ECMAScript was released, with support for strict mode. In strict mode, this is no longer bound to the global object but to undefined.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I dealed with this issue today and upgrading my webdrivermanger solved it for me (My previous version was 3.0.0):

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>3.3.0</version>
    <scope>test</scope>
</dependency>

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Import a module from a relative path

Relative sys.path example:

# /lib/my_module.py
# /src/test.py


if __name__ == '__main__' and __package__ is None:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module

Based on this answer.

How to check if two words are anagrams

I saw that no one has used the "hashcode" approach to find out the anagrams. I found my approach little different than the approaches discussed above hence thought of sharing it. I wrote the below code to find the anagrams which works in O(n).

/**
 * This class performs the logic of finding anagrams
 * @author ripudam
 *
 */
public class AnagramTest {

    public static boolean isAnagram(final String word1, final String word2) {

            if (word1 == null || word2 == null || word1.length() != word2.length()) {
                 return false;
            }

            if (word1.equals(word2)) {
                return true;
            }

            final AnagramWrapper word1Obj = new AnagramWrapper(word1);
            final AnagramWrapper word2Obj = new AnagramWrapper(word2);

            if (word1Obj.equals(word2Obj)) {
                return true;
            }

            return false;
        }

        /*
         * Inner class to wrap the string received for anagram check to find the
         * hash
         */
        static class AnagramWrapper {
            String word;

            public AnagramWrapper(final String word) {
                this.word = word;
            }

            @Override
            public boolean equals(final Object obj) {

                return hashCode() == obj.hashCode();
            }

            @Override
            public int hashCode() {
                final char[] array = word.toCharArray();
                int hashcode = 0;
                for (final char c : array) {
                    hashcode = hashcode + (c * c);
                }
                return hashcode;
            }
         }
    }

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

Set content of HTML <span> with Javascript

To do it without using a JavaScript library such as jQuery, you'd do it like this:

var span = document.getElementById("myspan"),
    text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);

If you do want to use jQuery, it's just this:

$("#myspan").text(''+intValue);

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

How to use JavaScript to change the form action

If you're using jQuery, it's as simple as this:

$('form').attr('action', 'myNewActionTarget.html');

SQL: how to select a single id ("row") that meets multiple criteria from a single column

I was having a similar issue like yours, except that I wanted a specific subset of 'ancestry'. Hong Ning's query was a good start, except it will return combined records containing duplicates and/or extra ancestries (e.g. it would also return someone with ancestries ('England', 'France', 'Germany', 'Netherlands') and ('England', 'France', 'England'). Supposing you'd want just the three and only the three, you'd need the following query:

SELECT Src.user_id
FROM yourtable Src
WHERE ancestry in ('England', 'France', 'Germany')
    AND EXISTS (
        SELECT user_id
        FROM dbo.yourtable
        WHERE user_id = Src.user_id
        GROUP BY user_id
        HAVING COUNT(DISTINCT ancestry) = 3
        )
GROUP BY user_id
HAVING COUNT(DISTINCT ancestry) = 3

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I have encounterd the same issue, but I find a anwser showing below.

web.xml

 <!-- set this param value for the filter-->
    <init-param>
            <param-name>freePages</param-name>
            <param-value>
            MainFrame.jsp;
            </param-value>
    </init-param>

filter.java

strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage)  //decide the exclude path

this way you don't have to harass the concrete Filter class.

How do I manually configure a DataSource in Java?

Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

 DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

 String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

 Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here.

EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

How to get the IP address of the server on which my C# application is running on?

WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");

Python equivalent to 'hold on' in Matlab

check pyplot docs. For completeness,

import numpy as np
import matplotlib.pyplot as plt

#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

How to convert string values from a dictionary, into int/float datatypes?

Gotta love list comprehensions.

[dict([a, int(x)] for a, x in b.items()) for b in list]

(remark: for Python 2 only code you may use "iteritems" instead of "items")

Can you use Microsoft Entity Framework with Oracle?

In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.

http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.

Each user must grant the user_friends permission in order to appear in the response to /me/friends.

let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
    if (error == nil) {

        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        if fbloginresult.grantedPermissions != nil {
            if (fbloginresult.grantedPermissions.contains("email")) {
                // Do the stuff
            }
            else {
            }
        }
        else {
        }
    }
}

So at the time of Facebook login, it prompts with a screen which contain all the permissions:

Enter image description here

If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed

if ((FBSDKAccessToken.current()) != nil) {
    FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
        if (error == nil) {

            print(result!)
        }
    })
}

The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.

{
    data = (
             {
                 id = xxxxxxxxxx;
                 name = "xxxxxxxx";
             }
           );
    paging = {
        cursors = {
            after = xxxxxx;
            before = xxxxxxx;
        };
    };
    summary = {
        "total_count" = 8;
    };
}

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I was facing this issue in Grafana and all I had to do was go to the config file and change allow_embedding to true and restart the server :)

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

You can find API KEY from the google-services.json file

Detect backspace and del on "input" event?

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Supported Browsers

How do I set up curl to permanently use a proxy?

One notice. On Windows, place your _curlrc in '%APPDATA%' or '%USERPROFILE%\Application Data'.

Common elements comparison between 2 lists

this is my proposition i think its easier with sets than with a for loop

def unique_common_items(list1, list2):
   # Produce the set of *unique* common items in two lists.
   return list(set(list1) & set(list2))

Postgres: INSERT if does not exist already

I know this question is from a while ago, but thought this might help someone. I think the easiest way to do this is via a trigger. E.g.:

Create Function ignore_dups() Returns Trigger
As $$
Begin
    If Exists (
        Select
            *
        From
            hundred h
        Where
            -- Assuming all three fields are primary key
            h.name = NEW.name
            And h.hundred_slug = NEW.hundred_slug
            And h.status = NEW.status
    ) Then
        Return NULL;
    End If;
    Return NEW;
End;
$$ Language plpgsql;

Create Trigger ignore_dups
    Before Insert On hundred
    For Each Row
    Execute Procedure ignore_dups();

Execute this code from a psql prompt (or however you like to execute queries directly on the database). Then you can insert as normal from Python. E.g.:

sql = "Insert Into hundreds (name, name_slug, status) Values (%s, %s, %s)"
cursor.execute(sql, (hundred, hundred_slug, status))

Note that as @Thomas_Wouters already mentioned, the code above takes advantage of parameters rather than concatenating the string.

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

Convert a byte array to integer in Java and vice versa

byte[] toByteArray(int value) {
     return  ByteBuffer.allocate(4).putInt(value).array();
}

byte[] toByteArray(int value) {
    return new byte[] { 
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)value };
}

int fromByteArray(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, | 
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
     return ((bytes[0] & 0xFF) << 24) | 
            ((bytes[1] & 0xFF) << 16) | 
            ((bytes[2] & 0xFF) << 8 ) | 
            ((bytes[3] & 0xFF) << 0 );
}

When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).

There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int

byte[] bytes = (…)
if (bytes[0] == 0xFF) {
   // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}

Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.

Error: Configuration with name 'default' not found in Android Studio

I also faced the same problem and the problem was that the libraries were missing in some of the following files.

settings.gradle, app/build.gradle, package.json, MainApplication.java

Suppose the library is react-native-vector-icons then it should be mentioned in following files;

In app/build.gradle file under dependencies section add:

compile project(':react-native-vector-icons')

In settings.gradle file under android folder, add the following:

include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')

In MainApplication.java, add the following:

Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;

and then add: new VectorIconsPackage() in getPackages() method.

XML Parser for C

Two of the most widely used parsers are Expat and libxml.

If you are okay with using C++, there's Xerces-C++ too.

ReferenceError: describe is not defined NodeJs

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).

People often tend to confuse java.lang.NoClassDefFoundError with java.lang.ClassNotFoundException however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError is a subclass of java.lang.Error) like

java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory

does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.

On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.

private static SomeClass foo = new SomeClass();

Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.

If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.

Convert DOS line endings to Linux line endings in Vim

From Wikia:

%s/\r\+$//g

That will find all carriage return signs (one and more reps) up to the end of line and delete, so just \n will stay at EOL.

python: sys is not defined

I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.

try:

import sys
# .. other safe imports
try:
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

How to read integer values from text file

You might want to do something like this (if you're using java 5 and more)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
     tall[i++] = scanner.nextInt();
}

Via Julian Grenier from Reading Integers From A File In An Array

Array initializing in Scala

Another way of declaring multi-dimentional arrays:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))

momentJS date string add 5 days

var end_date = moment(start_date).clone().add(5, 'days');

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

How do you create a yes/no boolean field in SQL server?

bit will be the simplest and also takes up the least space. Not very verbose compared to "Y/N" but I am fine with it.

How to round an image with Glide library?

With glide library you can use this code:

Glide.with(context)
    .load(imageUrl)
    .asBitmap()
    .placeholder(R.drawable.user_pic)
    .centerCrop()
    .into(new BitmapImageViewTarget(img_profPic) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);

            circularBitmapDrawable.setCircular(true);
            img_profPic.setImageDrawable(circularBitmapDrawable);
        }
    });

Print array elements on separate lines in Bash?

You could use a Bash C Style For Loop to do what you want.

my_array=(one two three)

for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three

How to emit an event from parent to child?

Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.

Center HTML Input Text Field Placeholder

You can use set in a class like below and set to input text class
CSS:

 .place-holder-center::placeholder {
        text-align: center;
    }

HTML:

<input type="text" class="place-holder-center">

Real world use of JMS/message queues?

We are using JMS for communication with systems in a huge number of remote sites over unreliable networks. The loose coupling in combination with reliable messaging produces a stable system landscape: Each message will be sent as soon it is technically possible, bigger problems in network will not have influence on the whole system landscape...

Not able to start Genymotion device

I've had this issue and none of the suggestions I found anywhere helped, unfortunately. The good news, however, is that the latest versions work without any hacks! I'm referring to Windows 7 host here.

genymotion-2.5.4.exe

VirtualBox-5.0.5-102814-Win.exe (download from test builds)

Edit: This stopped working again after updates so I gave up on Genymotion. The new Android emulator in SDK performs just as well, has great functionaly, and works without hiccups.

How do you get a query string on Flask?

If the request if GET and we passed some query parameters then,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)

git stash blunder: git stash pop and ended up with merge conflicts

I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add and then just did git reset. This basically just added and then unstaged my changes but cleared the unmerged paths.

Redirecting unauthorized controller in ASP.NET MVC

You can work with the overridable HandleUnauthorizedRequest inside your custom AuthorizeAttribute

Like this:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    // Returns HTTP 401 by default - see HttpUnauthorizedResult.cs.
    filterContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary 
    {
        { "action", "YourActionName" },
        { "controller", "YourControllerName" },
        { "parameterName", "YourParameterValue" }
    });
}

You can also do something like this:

private class RedirectController : Controller
{
    public ActionResult RedirectToSomewhere()
    {
        return RedirectToAction("Action", "Controller");
    }
}

Now you can use it in your HandleUnauthorizedRequest method this way:

filterContext.Result = (new RedirectController()).RedirectToSomewhere();

How do I convert Long to byte[] and back in java

Here's another way to convert byte[] to long using Java 8 or newer:

private static int bytesToInt(final byte[] bytes, final int offset) {
    assert offset + Integer.BYTES <= bytes.length;

    return (bytes[offset + Integer.BYTES - 1] & 0xFF) |
            (bytes[offset + Integer.BYTES - 2] & 0xFF) << Byte.SIZE |
            (bytes[offset + Integer.BYTES - 3] & 0xFF) << Byte.SIZE * 2 |
            (bytes[offset + Integer.BYTES - 4] & 0xFF) << Byte.SIZE * 3;
}

private static long bytesToLong(final byte[] bytes, final int offset) {
    return toUnsignedLong(bytesToInt(bytes, offset)) << Integer.SIZE |
            toUnsignedLong(bytesToInt(bytes, offset + Integer.BYTES));
}

Converting a long can be expressed as the high- and low-order bits of two integer values subject to a bitwise-OR. Note that the toUnsignedLong is from the Integer class and the first call to toUnsignedLong may be superfluous.

The opposite conversion can be unrolled as well, as others have mentioned.

Create directories using make file

make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget

This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

# The pipe symbol tells make that the following prerequisites are order-only
#                           |
#                           v
outDir/someTarget: Makefile | outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

This correctly yields:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.

TL;DR:

Write a rule to create the directory:

$(OUT_DIR):
    mkdir -p $(OUT_DIR)

And have the targets for the stuff inside depend on the directory order-only:

$(OUT_DIR)/someTarget: ... | $(OUT_DIR)

Android : How to read file in bytes?

Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:

byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}

NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.

EOFError: EOF when reading a line

convert your inputs to ints:

width = int(input())
height = int(input())

Floating point vs integer calculations on modern hardware

For example (lesser numbers are faster),

64-bit Intel Xeon X5550 @ 2.67GHz, gcc 4.1.2 -O3

short add/sub: 1.005460 [0]
short mul/div: 3.926543 [0]
long add/sub: 0.000000 [0]
long mul/div: 7.378581 [0]
long long add/sub: 0.000000 [0]
long long mul/div: 7.378593 [0]
float add/sub: 0.993583 [0]
float mul/div: 1.821565 [0]
double add/sub: 0.993884 [0]
double mul/div: 1.988664 [0]

32-bit Dual Core AMD Opteron(tm) Processor 265 @ 1.81GHz, gcc 3.4.6 -O3

short add/sub: 0.553863 [0]
short mul/div: 12.509163 [0]
long add/sub: 0.556912 [0]
long mul/div: 12.748019 [0]
long long add/sub: 5.298999 [0]
long long mul/div: 20.461186 [0]
float add/sub: 2.688253 [0]
float mul/div: 4.683886 [0]
double add/sub: 2.700834 [0]
double mul/div: 4.646755 [0]

As Dan pointed out, even once you normalize for clock frequency (which can be misleading in itself in pipelined designs), results will vary wildly based on CPU architecture (individual ALU/FPU performance, as well as actual number of ALUs/FPUs available per core in superscalar designs which influences how many independent operations can execute in parallel -- the latter factor is not exercised by the code below as all operations below are sequentially dependent.)

Poor man's FPU/ALU operation benchmark:

#include <stdio.h>
#ifdef _WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif
#include <time.h>
#include <cstdlib>

double
mygettime(void) {
# ifdef _WIN32
  struct _timeb tb;
  _ftime(&tb);
  return (double)tb.time + (0.001 * (double)tb.millitm);
# else
  struct timeval tv;
  if(gettimeofday(&tv, 0) < 0) {
    perror("oops");
  }
  return (double)tv.tv_sec + (0.000001 * (double)tv.tv_usec);
# endif
}

template< typename Type >
void my_test(const char* name) {
  Type v  = 0;
  // Do not use constants or repeating values
  //  to avoid loop unroll optimizations.
  // All values >0 to avoid division by 0
  // Perform ten ops/iteration to reduce
  //  impact of ++i below on measurements
  Type v0 = (Type)(rand() % 256)/16 + 1;
  Type v1 = (Type)(rand() % 256)/16 + 1;
  Type v2 = (Type)(rand() % 256)/16 + 1;
  Type v3 = (Type)(rand() % 256)/16 + 1;
  Type v4 = (Type)(rand() % 256)/16 + 1;
  Type v5 = (Type)(rand() % 256)/16 + 1;
  Type v6 = (Type)(rand() % 256)/16 + 1;
  Type v7 = (Type)(rand() % 256)/16 + 1;
  Type v8 = (Type)(rand() % 256)/16 + 1;
  Type v9 = (Type)(rand() % 256)/16 + 1;

  double t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v += v0;
    v -= v1;
    v += v2;
    v -= v3;
    v += v4;
    v -= v5;
    v += v6;
    v -= v7;
    v += v8;
    v -= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s add/sub: %f [%d]\n", name, mygettime() - t1, (int)v&1);
  t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v /= v0;
    v *= v1;
    v /= v2;
    v *= v3;
    v /= v4;
    v *= v5;
    v /= v6;
    v *= v7;
    v /= v8;
    v *= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s mul/div: %f [%d]\n", name, mygettime() - t1, (int)v&1);
}

int main() {
  my_test< short >("short");
  my_test< long >("long");
  my_test< long long >("long long");
  my_test< float >("float");
  my_test< double >("double");

  return 0;
}

How to select rows that have current day's timestamp?

SELECT * FROM `table` WHERE timestamp >= CURDATE()

it is shorter , there is no need to use 'AND timestamp < CURDATE() + INTERVAL 1 DAY'

because CURDATE() always return current day

MySQL CURDATE() Function

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

Create a new column with the desired column name: COLNew.

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Copy contents of old column COLOld to new column COLNew.

INSERT INTO {tableName} (COLNew) SELECT {COLOld} FROM {tableName}

Note: brackets are necessary in above line.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

In my case I called the method GetFilter() on an adapter from the TextWatcher() method on main Activity, and I added the data with a For loop on GetFilter(). The solution was change the For loop to AfterTextChanged() sub method on main Activity and delete the call to GetFilter()

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

Decimal values in SQL for dividing results

CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);