Programs & Examples On #Type signature

How to retrieve the first word of the output of a command in bash?

echo "word1 word2" | cut -f 1 -d " "

cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

Android Studio suddenly cannot resolve symbols

Another way is to download JDK 1.7 and change the path from Android Studio in the error message..and choose Home folder who is contained in Jdk 1.7 folder

How can I revert multiple Git commits (already pushed) to a published repository?

The Problem

There are a number of work-flows you can use. The main point is not to break history in a published branch unless you've communicated with everyone who might consume the branch and are willing to do surgery on everyone's clones. It's best not to do that if you can avoid it.

Solutions for Published Branches

Your outlined steps have merit. If you need the dev branch to be stable right away, do it that way. You have a number of tools for Debugging with Git that will help you find the right branch point, and then you can revert all the commits between your last stable commit and HEAD.

Either revert commits one at a time, in reverse order, or use the <first_bad_commit>..<last_bad_commit> range. Hashes are the simplest way to specify the commit range, but there are other notations. For example, if you've pushed 5 bad commits, you could revert them with:

# Revert a series using ancestor notation.
git revert --no-edit dev~5..dev

# Revert a series using commit hashes.
git revert --no-edit ffffffff..12345678

This will apply reversed patches to your working directory in sequence, working backwards towards your known-good commit. With the --no-edit flag, the changes to your working directory will be automatically committed after each reversed patch is applied.

See man 1 git-revert for more options, and man 7 gitrevisions for different ways to specify the commits to be reverted.

Alternatively, you can branch off your HEAD, fix things the way they need to be, and re-merge. Your build will be broken in the meantime, but this may make sense in some situations.

The Danger Zone

Of course, if you're absolutely sure that no one has pulled from the repository since your bad pushes, and if the remote is a bare repository, then you can do a non-fast-forward commit.

git reset --hard <last_good_commit>
git push --force

This will leave the reflog intact on your system and the upstream host, but your bad commits will disappear from the directly-accessible history and won't propagate on pulls. Your old changes will hang around until the repositories are pruned, but only Git ninjas will be able to see or recover the commits you made by mistake.

Fatal error: Cannot use object of type stdClass as array in

Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

RegEx: Grabbing values between quotation marks

If you're trying to find strings that only have a certain suffix, such as dot syntax, you can try this:

\"([^\"]*?[^\"]*?)\".localized

Where .localized is the suffix.

Example:

print("this is something I need to return".localized + "so is this".localized + "but this is not")

It will capture "this is something I need to return".localized and "so is this".localized but not "but this is not".

Counting the Number of keywords in a dictionary in python

In order to count the number of keywords in a dictionary:

def dict_finder(dict_finders):
    x=input("Enter the thing you want to find: ")
    if x in dict_finders:
        print("Element found")
    else:
        print("Nothing found:")

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to update the constant height constraint of a UIView programmatically?

If the above method does not work then make sure you update it in Dispatch.main.async{} block. You do not need to call layoutIfNeeded() method then.

Declaring an enum within a class

  1. If Color is something that is specific to just Cars then that is the way you would limit its scope. If you are going to have another Color enum that other classes use then you might as well make it global (or at least outside Car).

  2. It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify Car::Color in the function's interface.

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

How to capture UIView to UIImage without loss of quality on retina display

To improve answers by @Tommy and @Dima, use the following category to render UIView into UIImage with transparent background and without loss of quality. Working on iOS7. (Or just reuse that method in implementation, replacing self reference with your image)

UIView+RenderViewToImage.h

#import <UIKit/UIKit.h>

@interface UIView (RenderToImage)

- (UIImage *)imageByRenderingView;

@end

UIView+RenderViewToImage.m

#import "UIView+RenderViewToImage.h"

@implementation UIView (RenderViewToImage)

- (UIImage *)imageByRenderingView
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

@end

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

How to show hidden divs on mouseover?

There is a really simple way to do this in a CSS only way.

Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.

_x000D_
_x000D_
#mouse_over {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using Python 3 in virtualenv

For those having troubles while working with Anaconda3 (Python 3).

You could use

conda create -n name_of_your_virtualenv python=python_version 

To activate the environment ( Linux, MacOS)

source activate name_of_your_virtualenv

For Windows

activate name_of_your_virtualenv

How to scroll the page when a modal dialog is longer than the screen?

This is what fixed it for me:

max-height: 100%;
overflow-y: auto;

EDIT: I now use the same method currently used on Twitter where the modal acts sort of like a separate page on top of the current content and the content behind the modal does not move as you scroll.

In essence it is this:

var scrollBarWidth = window.innerWidth - document.body.offsetWidth;
$('body').css({
  marginRight: scrollBarWidth,
  overflow: 'hidden'
});
$modal.show();

With this CSS on the modal:

position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;

JSFiddle: https://jsfiddle.net/0x0049/koodkcng/
Pure JS version (IE9+): https://jsfiddle.net/0x0049/koodkcng/1/

This works no matter the height or width of the page or modal dialog, allows scrolling no matter where your mouse/finger is, doesn't have the jarring jump some solutions have that disable scroll on the main content, and looks great too.

XAMPP, Apache - Error: Apache shutdown unexpectedly

I had the exact same error message as the OP, but my problem was not addressed by any of the existing answers. Many of the answers deal with conflicts on port 80, which I knew I did not have, since I had had localhost responding on port 80 very recently.

Turns out I had inadvertently changed ServerRoot when I intended to change DocumentRoot (stupid, I know), and though the new ServerRoot directory existed, it did not contain the configuration files and other stuff apache needed, which caused it to fail on startup. The error message probably addresses this scenario by the wording 'missing dependencies'.

On my Windows system, setting ServerRoot back to C:/XAMPP/apache solved the problem.

jQuery Validate Required Select

It's simple, you need to get the Select field value and it cannot be "default".

if($('select').val()=='default'){
    alert('Please, choose an option');
    return false;
}

How to define a two-dimensional array?

Using NumPy you can initialize empty matrix like this:

import numpy as np
mm = np.matrix([])

And later append data like this:

mm = np.append(mm, [[1,2]], axis=1)

append multiple values for one key in a dictionary

You would be best off using collections.defaultdict (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list).

So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.

A quick example using your data:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.

Pycharm: run only part of my Python file

Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e

For this to work properly, you'll have to run everything this way.

enter image description here

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

If you want an index to be used and the query not to do a table scan:

WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY

To show the difference that this makes on the actual execution plans, we'll test with an SQL-Fiddle (an extremely helpful site):

CREATE TABLE test                            --- simple table
    ( id INT NOT NULL AUTO_INCREMENT
    ,`timestamp` datetime                    --- index timestamp
    , data VARCHAR(100) NOT NULL 
          DEFAULT 'Sample data'
    , PRIMARY KEY (id)
    , INDEX t_IX (`timestamp`, id)
    ) ;

INSERT INTO test
    (`timestamp`)
VALUES
    ('2013-02-08 00:01:12'),
    ---                                      --- insert about 7k rows
    ('2013-02-08 20:01:12') ;

Lets try the 2 versions now.


Version 1 with DATE(timestamp) = ?

EXPLAIN
SELECT * FROM test 
WHERE DATE(timestamp) = CURDATE()            ---  using DATE(timestamp)
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   ALL

ROWS  FILTERED  EXTRA
6671  100       Using where; Using filesort

It filters all (6671) rows and then does a filesort (that's not a problem as the returned rows are few)


Version 2 with timestamp <= ? AND timestamp < ?

EXPLAIN
SELECT * FROM test 
WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   range t_IX           t_IX    9 

ROWS  FILTERED  EXTRA
2     100       Using where

It uses a range scan on the index, and then reads only the corresponding rows from the table.

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

<script src="/script/login.js"></script>

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

Best practice to return errors in ASP.NET Web API

Use the built in "InternalServerError" method (available in ApiController):

return InternalServerError();
//or...
return InternalServerError(new YourException("your message"));

Content Type text/xml; charset=utf-8 was not supported by service

I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to

Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory" 

and now you can compile & run your application successfully.

How to display alt text for an image in chrome

Various browsers (mis)handle this in various ways. Using title (an old IE 'standard') isn't particularly appropriate, since the title attribute is a mouseover effect. The jQuery solution above (Alexis) seems on the right track, but I don't think the 'error' occurs at a point where it could be caught. I've had success by replacing at the src with itself, and then catching the error:

$('img').each(function()
{
    $(this).error(function()
    {
        $(this).replaceWith(this.alt);
    }).attr('src',$(this).prop('src'));
});

This, as in the Alexis contribution, has the benefit of removing the missing img image.

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

How to get the containing form of an input?

Native DOM elements that are inputs also have a form attribute that points to the form they belong to:

var form = element.form;
alert($(form).attr('name'));

According to w3schools, the .form property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.

If this were a different type of element (not an <input>), you could find the closest parent with closest:

var $form = $(element).closest('form');
alert($form.attr('name'));

Also, see this MDN link on the form property of HTMLInputElement:

jQuery select all except first

My answer is focused to a extended case derived from the one exposed at top.

Suppose you have group of elements from which you want to hide the child elements except first. As an example:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>
  1. We want to hide all .child elements on every group. So this will not help because will hide all .child elements except visible#1:

    $('.child:not(:first)').hide();
    
  2. The solution (in this extended case) will be:

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });
    

How to return JSON data from spring Controller using @ResponseBody

Add the below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

Bind class toggle to window scroll event

Maybe this can help :)

Controller

$scope.scrollevent = function($e){
   // Your code
}

Html

<div scroll scroll-event="scrollevent">//scrollable content</div>

Or

<body scroll scroll-event="scrollevent">//scrollable content</body>

Directive

.directive("scroll", function ($window) {
   return {
      scope: {
         scrollEvent: '&'
      },
      link : function(scope, element, attrs) {
        $("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ?  scope.scrollEvent()($e) : null })
      }
   }
})

How to create a new object instance from a Type

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

The Activator class has a generic variant that makes this a bit easier:

ObjectType instance = Activator.CreateInstance<ObjectType>();

How to sort Map values by key in Java?

Using the TreeMap you can sort the map.

Map<String, String> map = new HashMap<>();        
Map<String, String> treeMap = new TreeMap<>(map);
for (String str : treeMap.keySet()) {
    System.out.println(str);
}

How to preview a part of a large pandas DataFrame, in iPython notebook?

I found the following approach to be the most effective for sampling a DataFrame:

print(df[A:B]) ## 'A' and 'B' are the first and last records in range

For example, print(df[10:15]) will print rows 10 through 15 - inclusive - from your data set.

How to remove carriage return and newline from a variable in shell script

for a pure shell solution without calling external program:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

TSQL: How to convert local time to UTC? (SQL Server 2008)

While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.

That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.

Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

In the endpoint tag you need to include the property address=""

<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Try this,

 body.modal-open {
    overflow: hidden;
    position:fixed;
    width: 100%;
}

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

This worked for me:

Select
    dateadd(S, [unixtime], '1970-01-01')
From [Table]

In case any one wonders why 1970-01-01, This is called Epoch time.

Below is a quote from Wikipedia:

The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970,[1][note 1] not counting leap seconds.

How does bitshifting work in Java?

byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10

Regular Expression for any number greater than 0?

The simple answer is: ^[1-9][0-9]*$

Device not detected in Eclipse when connected with USB cable

ok this is an old thread -
but I spent nearly two days and did not get anywhere
Here is what solved my problem
I had USB debugging enabled ( finding developer options itself was a pain - I think the 7 times tap from google is childish and just plain stupid - rant over )

However HTC syn manager , eclipse ADT and windows computer management were all unable to identify my device

My problem was my phone was set to ONLY USB Charge - this was the problem In 'USB Computer connection' >> Choose the option USB Storage Once you do this - PC will install drivers and your device will get detected by Eclipse as well as in 'Computer Management' under ''Android USB devices '

Now I still dont know a way to access ''USB Computer connection' but at that time I did get the option to change and t worked

For those ( like me earlier ) who dont know how to identify if 'Computer Management' shows their device look for 'Android USB devices ' If its present - then your device is being detected by your PC

Hope this helps some others
shankar

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show variable is true, and perform the animation/transition via CSS.

So your minimum Angular code is this:

<div class="box-opener" (click)="show = !show">
    Open/close the box
</div>

<div class="box" [class.opened]="show">
    <!-- Content -->
</div>

With this solution, you need to create CSS rules for the transition, something like this:

.box {
    background-color: #FFCC55;
    max-height: 0px;
    overflow-y: hidden;
    transition: ease-in-out 400ms max-height;
}

.box.opened {
    max-height: 500px;
    transition: ease-in-out 600ms max-height;
}

If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transitions.

See the example here

ImportError: numpy.core.multiarray failed to import

In my case installing from apt solved my problem.

You can try uninstall it from pip and install from apt (if you are using ubuntu etc.)

pip3 uninstall numpy
sudo apt-get install python3-numpy

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Convert String (UTF-16) to UTF-8 in C#

class Program
{
    static void Main(string[] args)
    {
        String unicodeString =
        "This Unicode string contains two characters " +
        "with codes outside the traditional ASCII code range, " +
        "Pi (\u03a0) and Sigma (\u03a3).";

        Console.WriteLine("Original string:");
        Console.WriteLine(unicodeString);
        UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
        byte[] utf16Bytes = unicodeEncoding.GetBytes(unicodeString);
        char[] chars = unicodeEncoding.GetChars(utf16Bytes, 2, utf16Bytes.Length - 2);
        string s = new string(chars);
        Console.WriteLine();
        Console.WriteLine("Char Array:");
        foreach (char c in chars) Console.Write(c);
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("String from Char Array:");
        Console.WriteLine(s);

        Console.ReadKey();
    }
}

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

I solved by following these steps:

  • Right click in the project > Configure > Convert to Maven project
  • After the conversion, right click in the project > Maven > Update project

This fixes the "Deployment Assembly" settings of the project.

How to get the full url in Express?

You need to construct it using req.headers.host + req.url. Of course if you are hosting in a different port and such you get the idea ;-)

Android studio - Failed to find target android-18

This will also happen if you have written compileSdkVersion = 22 e.g. (as used in the "new new" Android build system) instead of compileSdkVersion 22.

How to change a <select> value from JavaScript

document.getElementById("select").selectedIndex = 0 will work

Find if value in column A contains value from column B?

You can use VLOOKUP, but this requires a wrapper function to return True or False. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.

Fill down this formula in column K next to the existing values in column I (from I1 to I2691):

=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0

You can also use MATCH:

=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))

UICollectionView Set number of columns

I made a collection layout.

To make the separator visible, Set the background color of the collection view to gray. One row per section.

Useage:

let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50  // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout

Layout:

import UIKit

class GridCollectionViewLayout: UICollectionViewLayout {


var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1

private var cache = [UICollectionViewLayoutAttributes]()



override func prepare() {

    guard let collectionView = self.collectionView else {
        return
    }

    self.cache.removeAll()



        let numberOfSections = collectionView.numberOfSections

        if cellHeight <= 0
        {
            cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
        }

        for section in 0..<collectionView.numberOfSections {

            let numberOfItems = collectionView.numberOfItems(inSection: section)

            let cellWidth2 : CGFloat
            if cellWidth <= 0
            {
                cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
            }
            else
            {
                cellWidth2 = cellWidth
            }


            for row in 0..<numberOfItems {


                let indexPath = NSIndexPath(row: row, section: section)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
                                          y: (cellHeight+seperator)*CGFloat(section),
                                          width: cellWidth2,
                                          height: cellHeight)

                //row_temp.append(attributes)

                self.cache.append(attributes)
            }
            //self.itemAttributes.append(row_temp)
        }

}

override var collectionViewContentSize: CGSize {

    guard let collectionView = collectionView else
    {
        return CGSize.zero
    }

    if (collectionView.numberOfSections <= 0)
    {
        return collectionView.bounds.size
    }

    let width:CGFloat
    if cellWidth <= 0
    {
        width = collectionView.bounds.width
    }
    else
    {
        width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
    }

    let numberOfSections = CGFloat(collectionView.numberOfSections)
    var height:CGFloat = 0
    height += numberOfSections * cellHeight
    height += (numberOfSections - 1) * seperator



    return CGSize(width: width, height: height)
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
}
}

Ignore <br> with CSS?

You can simply convert it in a comment..

Or you can do this:

br {
display: none;
}

But if you do not want it why are you puting that there?

Array functions in jQuery

You can use Underscore.js. It really makes things simple.

For example, removing elements from an array, you need to do:

_.without([1, 2, 3], 2);

And the result will be [1, 3].

It reduces the code that you write using jQuery.grep, etc. in jQuery.

How do I pass data to Angular routed components?

Pass using JSON

  <a routerLink = "/link"
   [queryParams] = "{parameterName: objectToPass| json }">
         sample Link                   
  </a>

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

What are allowed characters in cookies?

There is another interesting issue with IE and Edge. Cookies that have names with more than 1 period seem to be silently dropped. So This works:

cookie_name_a=valuea

while this will get dropped

cookie.name.a=valuea

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.

This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

The solution from parisjohn above works fine with me. Plus the code looks clean and easy to understand. In my case there are a few functions to call using Pool, so I modified parisjohn's code a bit below. I made call to be able to call several functions, and the function names are passed in the argument dict from go():

from multiprocessing import Pool
class someClass(object):
    def __init__(self):
        pass

    def f(self, x):
        return x*x

    def g(self, x):
        return x*x+1    

    def go(self):
        p = Pool(4)
        sc = p.map(self, [{"func": "f", "v": 1}, {"func": "g", "v": 2}])
        print sc

    def __call__(self, x):
        if x["func"]=="f":
            return self.f(x["v"])
        if x["func"]=="g":
            return self.g(x["v"])        

sc = someClass()
sc.go()

How to create a custom navigation drawer in android

Android Navigation Drawer using Activity I just followed the example :http://antonioleiva.com/navigation-view/

You just need few Customization:

public class MainActivity extends AppCompatActivity  {

public static final String AVATAR_URL = "http://lorempixel.com/200/200/people/1/";


private DrawerLayout drawerLayout;
private View content;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    initToolbar();
    setupDrawerLayout();

    content = findViewById(R.id.content);
    drawerToggle = setupDrawerToggle();
    final ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.avatar);
    Picasso.with(this).load(AVATAR_URL).transform(new CircleTransform()).into(avatar);


}


private void initToolbar() {
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}
private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

   @Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    drawerToggle.onConfigurationChanged(newConfig);
}
 private void setupDrawerLayout() {

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            int id = menuItem.getItemId();

          switch (id) {
                case R.id.drawer_home:
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                    finish();
                    break;
                case R.id.drawer_favorite:
                    Intent j = new Intent(getApplicationContext(), SecondActivity.class);
                    startActivity(j);
                    finish();
                    break;

            }


        return true;
    }
});

} Here is the xml Layout

<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap" />

    </android.support.design.widget.AppBarLayout>



</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/drawer"/>

Add drawer.xml in menu

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group
    android:checkableBehavior="single">

    <item
        android:id="@+id/drawer_home"
        android:checked="true"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home"/>

    <item
        android:id="@+id/drawer_favourite"
        android:icon="@drawable/ic_favorite_black_24dp"
        android:title="@string/favourite"/>
    ...

    <item
        android:id="@+id/drawer_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/settings"/>

</group>

To open and close drawer add this values in string.xml

<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>

drawer.xml

enter code here

<ImageView
    android:id="@+id/avatar"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_margin="@dimen/spacing_large"
    android:elevation="4dp"
    tools:src="@drawable/ic_launcher"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/email"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:text="Username"
    android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:layout_marginBottom="@dimen/spacing_large"
    android:text="[email protected]"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

How does the FetchMode work in Spring Data JPA

I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph and @EntityGraph annotations when working with Spring Data

@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

Check the documentation here

Static Initialization Blocks

It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):

public enum Language { 
  ENGLISH("eng", "en", "en_GB", "en_US"),   
  GERMAN("de", "ge"),   
  CROATIAN("hr", "cro"),   
  RUSSIAN("ru"),
  BELGIAN("be",";-)");

  static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>(); 
  static { 
    for (Language l:Language.values()) { 
      // ignoring the case by normalizing to uppercase
      ALIAS_MAP.put(l.name().toUpperCase(),l); 
      for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l); 
    } 
  } 

  static public boolean has(String value) { 
    // ignoring the case by normalizing to uppercase
    return ALIAS_MAP.containsKey(value.toUpper()); 
  } 

  static public Language fromString(String value) { 
    if (value == null) throw new NullPointerException("alias null"); 
    Language l = ALIAS_MAP.get(value); 
    if (l == null) throw new IllegalArgumentException("Not an alias: "+value); 
    return l; 
  } 

  private List<String> aliases; 
  private Language(String... aliases) { 
    this.aliases = Arrays.asList(aliases); 
  } 
} 

Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.

As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:

  1. The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
  2. static block and initialization of static fields in the order of occurrence.

This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):

public class Foo {
  static { System.out.println("Static Block 1"); }
  public static final Foo FOO = new Foo();
  static { System.out.println("Static Block 2"); }
  public Foo() { System.out.println("Constructor"); }
  static public void main(String p[]) {
    System.out.println("In Main");
    new Foo();
  }
}

What we see is the following output:

Static Block 1
Constructor
Static Block 2
In Main
Constructor

Clear is that the static initialization actually can happen before the constructor, and even after:

Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.

For more info on this see the book "Effective Java".

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

Find the directory part (minus the filename) of a full path in access 97

If you're just needing the path of the MDB currently open in the Access UI, I'd suggest writing a function that parses CurrentDB.Name and then stores the result in a Static variable inside the function. Something like this:

Public Function CurrentPath() As String
  Dim strCurrentDBName As String
  Static strPath As String
  Dim i As Integer

  If Len(strPath) = 0 Then
     strCurrentDBName = CurrentDb.Name
     For i = Len(strCurrentDBName) To 1 Step -1
       If Mid(strCurrentDBName, i, 1) = "\" Then
          strPath = Left(strCurrentDBName, i)
          Exit For
       End If
    Next
  End If
  CurrentPath = strPath
End Function

This has the advantage that it only loops through the name one time.

Of course, it only works with the file that's open in the user interface.

Another way to write this would be to use the functions provided at the link inside the function above, thus:

Public Function CurrentPath() As String
  Static strPath As String

  If Len(strPath) = 0 Then
     strPath = FolderFromPath(CurrentDB.Name)
  End If
  CurrentPath = strPath
End Function

This makes retrieving the current path very efficient while utilizing code that can be used for finding the path for any filename/path.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

To specify a Dockerfile when build, you can use:

docker build -t ubuntu-test:latest - < /path/to/your/Dockerfile

But it'll fail if there's ADD or COPY command that depends on relative path. There're many ways to specify a context for docker build, you can refer to docs of docker build for more info.

Sql Server string to date conversion

If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.

How do I "commit" changes in a git submodule?

$ git submodule status --recursive

Is also a life saver in this situation. You can use it and gitk --all to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

Can't include C++ headers like vector in Android NDK

This is what caused the problem in my case (CMakeLists.txt):

set (CMAKE_CXX_FLAGS "...some flags...")

It makes invisible all earlier defined include directories. After removing / refactoring this line everything works fine.

Plotting in a non-blocking way with Matplotlib

I spent a long time looking for solutions, and found this answer.

It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.

Here's an implementation that works for me on python 3.5:

import numpy as np
from matplotlib import pyplot as plt

def main():
    plt.axis([-50,50,0,10000])
    plt.ion()
    plt.show()

    x = np.arange(-50, 51)
    for pow in range(1,5):   # plot x^1, x^2, ..., x^4
        y = [Xi**pow for Xi in x]
        plt.plot(x, y)
        plt.draw()
        plt.pause(0.001)
        input("Press [enter] to continue.")

if __name__ == '__main__':
    main()

Hash Table/Associative Array in VBA

Here we go... just copy the code to a module, it's ready to use

Private Type hashtable
    key As Variant
    value As Variant
End Type

Private GetErrMsg As String

Private Function CreateHashTable(htable() As hashtable) As Boolean
    GetErrMsg = ""
    On Error GoTo CreateErr
        ReDim htable(0)
        CreateHashTable = True
    Exit Function

CreateErr:
    CreateHashTable = False
    GetErrMsg = Err.Description
End Function

Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
    GetErrMsg = ""
    On Error GoTo AddErr
        Dim idx As Long
        idx = UBound(htable) + 1

        Dim htVal As hashtable
        htVal.key = key
        htVal.value = value

        Dim i As Long
        For i = 1 To UBound(htable)
            If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
        Next i

        ReDim Preserve htable(idx)

        htable(idx) = htVal
        AddValue = idx
    Exit Function

AddErr:
    AddValue = 0
    GetErrMsg = Err.Description
End Function

Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
    GetErrMsg = ""
    On Error GoTo RemoveErr

        Dim i As Long, idx As Long
        Dim htTemp() As hashtable
        idx = 0

        For i = 1 To UBound(htable)
            If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
                ReDim Preserve htTemp(idx)
                AddValue htTemp, htable(i).key, htable(i).value
                idx = idx + 1
            End If
        Next i

        If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"

        htable = htTemp
        RemoveValue = True
    Exit Function

RemoveErr:
    RemoveValue = False
    GetErrMsg = Err.Description
End Function

Private Function GetValue(htable() As hashtable, key As Variant) As Variant
    GetErrMsg = ""
    On Error GoTo GetValueErr
        Dim found As Boolean
        found = False

        For i = 1 To UBound(htable)
            If htable(i).key = key And IsEmpty(htable(i).key) = False Then
                GetValue = htable(i).value
                Exit Function
            End If
        Next i
        Err.Raise 9997, , "Key [" & CStr(key) & "] not found"

    Exit Function

GetValueErr:
    GetValue = ""
    GetErrMsg = Err.Description
End Function

Private Function GetValueCount(htable() As hashtable) As Long
    GetErrMsg = ""
    On Error GoTo GetValueCountErr
        GetValueCount = UBound(htable)
    Exit Function

GetValueCountErr:
    GetValueCount = 0
    GetErrMsg = Err.Description
End Function

To use in your VB(A) App:

Public Sub Test()
    Dim hashtbl() As hashtable
    Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
    Debug.Print ""
    Debug.Print "ID Test   Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test   Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
    Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
    Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
    Debug.Print ""
    Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
    Debug.Print ""
    Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
    Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
    Debug.Print ""
    Debug.Print "Hashtable Content:"

    For i = 1 To UBound(hashtbl)
        Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
    Next i

    Debug.Print ""
    Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub

How to pad a string to a fixed length with spaces in Python?

If you have python version 3.6 or higher you can use f strings

>>> string = "John"
>>> f"{string:<15}"
'John           '

Or if you'd like it to the left

>>> f"{string:>15}"
'          John'

Centered

>>> f"{string:^15}"
'     John      '

For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax

How to count the frequency of the elements in an unordered list?

Simple solution using a dictionary.

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

Button Listener for button in fragment in android

Your fragment class should implement OnClickListener

public class SmartTvControllerFragment extends Fragment implements View.OnClickListener

Then get view, link button and set onClickListener like in example below

 View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.smart_tv_controller_fragment, container, false);
    upButton = (Button) view.findViewById(R.id.smart_tv_controller_framgment_up_button);
    upButton.setOnClickListener(this);
    return view;
 }

And then add onClickListener method and do what you want.

@Override
public void onClick(View v) {
 //do what you want to do when button is clicked
    switch (v.getId()) {
        case R.id.textView_help:
            switchFragment(HelpFragment.TAG);
            break;
        case R.id.textView_settings:
            switchFragment(SettingsFragment.TAG);
            break;
    }
}

This is my example of code, but I hope you understood

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

How do I send a POST request with PHP?

I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Using Java to pull data from a webpage?

The Basics

Look at these to build a solution more or less from scratch:

The Easily Glued-Up and Stitched-Up Stuff

You always have the option of calling external tools from Java using the exec() and similar methods. For instance, you could use wget, or cURL.

The Hardcore Stuff

Then if you want to go into more fully-fledged stuff, thankfully the need for automated web-testing as given us very practical tools for this. Look at:

Some other libs are purposefully written with web-scraping in mind:

Some Workarounds

Java is a language, but also a platform, with many other languages running on it. Some of which integrate great syntactic sugar or libraries to easily build scrapers.

Check out:

If you know of a great library for Ruby (JRuby, with an article on scraping with JRuby and HtmlUnit) or Python (Jython) or you prefer these languages, then give their JVM ports a chance.

Some Supplements

Some other similar questions:

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

Create a simple 10 second countdown

A solution using Promises, includes both progress bar & text countdown.

_x000D_
_x000D_
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));_x000D_
_x000D_
function ProgressCountdown(timeleft, bar, text) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    var countdownTimer = setInterval(() => {_x000D_
      timeleft--;_x000D_
_x000D_
      document.getElementById(bar).value = timeleft;_x000D_
      document.getElementById(text).textContent = timeleft;_x000D_
_x000D_
      if (timeleft <= 0) {_x000D_
        clearInterval(countdownTimer);_x000D_
        resolve(true);_x000D_
      }_x000D_
    }, 1000);_x000D_
  });_x000D_
}
_x000D_
<div class="row begin-countdown">_x000D_
  <div class="col-md-12 text-center">_x000D_
    <progress value="10" max="10" id="pageBeginCountdown"></progress>_x000D_
    <p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);

For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).

Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.

For example, this will parse your date correctly:

DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );

Of course, you shouldn't just randomly pick France, but something appropriate to your needs.

What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.

How to get Top 5 records in SqLite?

SELECT * FROM Table_Name LIMIT 5;

How to link C++ program with Boost using CMake

The following is my configuration:

cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Remove all files except some from a directory

find . | grep -v "excluded files criteria" | xargs rm

This will list all files in current directory, then list all those that don't match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

mkdir /tmp_backup && mv textfile.txt backup.tar.gz script.php database.sql info.txt /tmp_backup/ && rm -r && mv /tmp_backup/* . && rmdir /tmp_backup

It will create a backup directory /tmp_backup (you've got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you're in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup.

I choose the backup directory to be in root, because if you're trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.

How to put an image in div with CSS?

This answer by Jaap :

<div class="image"></div>?

and in CSS :

div.image {
   content:url(http://placehold.it/350x150);
}?

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

Cannot catch toolbar home button click event

    mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
    mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // event when click home button
        }
    });

in mycase this code work perfect

How to fit Windows Form to any screen resolution?

Set the form property to open in maximized state.

this.WindowState = FormWindowState.Maximized;

MySQL Query to select data from last week?

If you already know the dates then you can simply use between, like this:

SELECT id    
FROM `Mytable`    
where MyDate BETWEEN "2011-05-15" AND "2011-05-21"

Use of #pragma in C

#pragma startup is a directive which is used to call a function before the main function and to call another function after the main function, e.g.

#pragma startup func1
#pragma exit func2

Here, func1 runs before main and func2 runs afterwards.

NOTE: This code works only in Turbo-C compiler. To achieve this functionality in GCC, you can declare func1 and func2 like this:

void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();

Jenkins Host key verification failed

Best way you can just use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.

git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'

Decoding JSON String in Java

This is the JSON String we want to decode :

{ 
   "stats": { 
       "sdr": "aa:bb:cc:dd:ee:ff", 
       "rcv": "aa:bb:cc:dd:ee:ff", 
       "time": "UTC in millis", 
       "type": 1, 
       "subt": 1, 
       "argv": [
          {"1": 2}, 
          {"2": 3}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

How to customize the configuration file of the official PostgreSQL Docker image?

This works for me:

FROM postgres:9.6
USER postgres

# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql

# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Use of var keyword in C#

Depends, somehow it makes the code look 'cleaner', but agree it makes it more unreadable to...

Loading an image to a <img> from <input file>

ES2017 Way

_x000D_
_x000D_
// convert file to a base64 url
const readURL = file => {
    return new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = e => res(e.target.result);
        reader.onerror = e => rej(e);
        reader.readAsDataURL(file);
    });
};

// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);

const preview = async event => {
    const file = event.target.files[0];
    const url = await readURL(file);
    img.src = url;
};

fileInput.addEventListener('change', preview);
_x000D_
_x000D_
_x000D_

Getting the IP Address of a Remote Socket Endpoint

string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();

How to convert date to timestamp?

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

How to add key,value pair to dictionary?

Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

How to manipulate arrays. Find the average. Beginner Java

-while(int i=0; i < data.length; i++) 
+for(int i=0; i < data.length; i++) 

jQuery .ready in a dynamically inserted iframe

This was the exact issue I ran into with our client. I created a little jquery plugin that seems to work for iframe readiness. It uses polling to check the iframe document readyState combined with the inner document url combined with the iframe source to make sure the iframe is in fact "ready".

The issue with "onload" is that you need access to the actual iframe being added to the DOM, if you don't then you need to try to catch the iframe loading which if it is cached then you may not. What I needed was a script that could be called anytime, and determine whether or not the iframe was "ready" or not.

Here's the question:

Holy grail for determining whether or not local iframe has loaded

and here's the jsfiddle I eventually came up with.

https://jsfiddle.net/q0smjkh5/10/

In the jsfiddle above, I am waiting for onload to append an iframe to the dom, then checking iframe's inner document's ready state - which should be cross domain because it's pointed to wikipedia - but Chrome seems to report "complete". The plug-in's iready method then gets called when the iframe is in fact ready. The callback tries to check the inner document's ready state again - this time reporting a cross domain request (which is correct) - anyway it seems to work for what I need and hope it helps others.

<script>
  (function($, document, undefined) {
    $.fn["iready"] = function(callback) {
      var ifr = this.filter("iframe"),
          arg = arguments,
          src = this,
          clc = null, // collection
          lng = 50,   // length of time to wait between intervals
          ivl = -1,   // interval id
          chk = function(ifr) {
            try {
              var cnt = ifr.contents(),
                  doc = cnt[0],
                  src = ifr.attr("src"),
                  url = doc.URL;
              switch (doc.readyState) {
                case "complete":
                  if (!src || src === "about:blank") {
                    // we don't care about empty iframes
                    ifr.data("ready", "true");
                  } else if (!url || url === "about:blank") {
                    // empty document still needs loaded
                    ifr.data("ready", undefined);
                  } else {
                    // not an empty iframe and not an empty src
                    // should be loaded
                    ifr.data("ready", true);
                  }

                  break;
                case "interactive":
                  ifr.data("ready", "true");
                  break;
                case "loading":
                default:
                  // still loading
                  break;   
              }
            } catch (ignore) {
              // as far as we're concerned the iframe is ready
              // since we won't be able to access it cross domain
              ifr.data("ready", "true");
            }

            return ifr.data("ready") === "true";
          };

      if (ifr.length) {
        ifr.each(function() {
          if (!$(this).data("ready")) {
            // add to collection
            clc = (clc) ? clc.add($(this)) : $(this);
          }
        });
        if (clc) {
          ivl = setInterval(function() {
            var rd = true;
            clc.each(function() {
              if (!$(this).data("ready")) {
                if (!chk($(this))) {
                  rd = false;
                }
              }
            });

            if (rd) {
              clearInterval(ivl);
              clc = null;
              callback.apply(src, arg);
            }
          }, lng);
        } else {
          clc = null;
          callback.apply(src, arg);
        }
      } else {
        clc = null;
        callback.apply(this, arguments);
      }
      return this;
    };
  }(jQuery, document));
</script>

How to make a round button?

I simply use a FloatingActionButton with elevation = 0dp to remove the shadow:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_send"
    app:elevation="0dp" />

Relative imports for the billionth time

Here is one solution that I would not recommend, but might be useful in some situations where modules were simply not generated:

import os
import sys
parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name + "/your_dir")
import your_script
your_script.a_function()

Handler vs AsyncTask vs Thread

It depends which one to chose is based on the requirement

Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread

If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper

AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance

Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.

Select all text inside EditText when it gets focus

You can also add an OnClick Method to the editText after

_editText.setSelectAllOnFocus(true);

and in that:

_editText.clearFocus();
_editText.requestFocus();

As soon as you click the editText the whole text is selected.

ReactJS SyntheticEvent stopPropagation() only works with React events?

React 17 delegates events to root instead of document, which might solve the problem. More details here.

How to reference static assets within vue javascript

In order for Webpack to return the correct asset paths, you need to use require('./relative/path/to/file.jpg'), which will get processed by file-loader and returns the resolved URL.

computed: {
  iconUrl () {
    return require('./assets/img.png')
    // The path could be '../assets/img.png', etc., which depends on where your vue file is
  }
}

See VueJS templates - Handling Static Assets

PRINT statement in T-SQL

Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:

RAISERROR ('Your message', 0, 1) WITH NOWAIT

RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.

Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.

Split string using a newline delimiter with Python

str.splitlines method should give you exactly that.

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

download file using an ajax request

Cross browser solution, tested on Chrome, Firefox, Edge, IE11.

In the DOM, add an hidden link tag:

<a id="target" style="display: none"></a>

Then:

var req = new XMLHttpRequest();
req.open("GET", downloadUrl, true);
req.responseType = "blob";
req.setRequestHeader('my-custom-header', 'custom-value'); // adding some headers (if needed)

req.onload = function (event) {
  var blob = req.response;
  var fileName = null;
  var contentType = req.getResponseHeader("content-type");

  // IE/EDGE seems not returning some response header
  if (req.getResponseHeader("content-disposition")) {
    var contentDisposition = req.getResponseHeader("content-disposition");
    fileName = contentDisposition.substring(contentDisposition.indexOf("=")+1);
  } else {
    fileName = "unnamed." + contentType.substring(contentType.indexOf("/")+1);
  }

  if (window.navigator.msSaveOrOpenBlob) {
    // Internet Explorer
    window.navigator.msSaveOrOpenBlob(new Blob([blob], {type: contentType}), fileName);
  } else {
    var el = document.getElementById("target");
    el.href = window.URL.createObjectURL(blob);
    el.download = fileName;
    el.click();
  }
};
req.send();

How to retrieve a module's path?

As the other answers have said, the best way to do this is with __file__ (demonstrated again below). However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own (i.e. as __main__).

For example, say you have two files (both of which are on your PYTHONPATH):

#/path1/foo.py
import bar
print(bar.__file__)

and

#/path2/bar.py
import os
print(os.getcwd())
print(__file__)

Running foo.py will give the output:

/path1        # "import bar" causes the line "print(os.getcwd())" to run
/path2/bar.py # then "print(__file__)" runs
/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs

HOWEVER if you try to run bar.py on its own, you will get:

/path2                              # "print(os.getcwd())" still works fine
Traceback (most recent call last):  # but __file__ doesn't exist if bar.py is running as main
  File "/path2/bar.py", line 3, in <module>
    print(__file__)
NameError: name '__file__' is not defined 

Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.

Python 3 Building an array of bytes

Here is a solution to getting an array (list) of bytes:

I found that you needed to convert the Int to a byte first, before passing it to the bytes():

bytes(int('0xA2', 16).to_bytes(1, "big"))

Then create a list from the bytes:

list(frame)

So your code should look like:

frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)

The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

This error is very common, often the very first one you get on trying to establish a connection to your database. I suggest those 6 steps to fix ORA-12154 :

  1. Check instance name has been entered correctly in tnsnames.ora.
  2. There should be no control characters at the end of the instance or database name.
  3. All paranthesis around the TNS entry should be properly terminated
  4. Domain name entry in sqlnet.ora should not be conflicting with full database name.
  5. If problem still persists, try to re-create TNS entry in tnsnames.ora.
  6. At last you may add new entries using the SQL*Net Easy configuration utility.

For more informations : http://turfybot.free.fr/oracle/11g/errors/ORA-12154.html

How to send control+c from a bash script?

    pgrep -f process_name > any_file_name
    sed -i 's/^/kill /' any_file_name
    chmod 777 any_file_name
    ./any_file_name

for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.

How to place two divs next to each other?

You can sit elements next to each other by using the CSS float property:

#first {
float: left;
}
#second {
float: left;
}

You'd need to make sure that the wrapper div allows for the floating in terms of width, and margins etc are set correctly.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The proper way is to use Hibernate Transformers:

public class StudentDTO {
private String studentName;
private String courseDescription;

public StudentDTO() { }  
...
} 

.

List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Iterating througth Object[] is redundant and would have some performance penalty. Detailed information about transofrmers usage you will find here: Transformers for HQL and SQL

If you are looking for even more simple solution you can use out-of-the-box-map-transformer:

List iter = s.createQuery(
"select e.student.name as studentName," +
"       e.course.description as courseDescription" +
"from   Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
.iterate();

String name = (Map)(iter.next()).get("studentName");

How to fully clean bin and obj folders within Visual Studio?

For Visual Studio 2015 the MSBuild variables have changed a bit:

  <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
         <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
         <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
         <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
  </Target>

Notice that this snippet also wipes out the .vs folder from the root directory of your solution. You may want to comment out the associated line if you feel that removing the .vs folder is an overkill. I have it enabled because I noticed that in some third party projects it causes issues when files ala application.config exist inside the .vs folder.

Addendum:

If you are into optimizing the maintainability of your solutions you might want to take things one step further and place the above snippet into a separate file like so:

  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
       <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
            <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
            <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
            <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
       </Target>
  </Project>

And then include this file at the very end of each and every one of your *.csproj files like so:

     [...]
     <Import Project="..\..\Tools\ExtraCleanup.targets"/>
  </Project>

This way you can enrich or fine-tune your extra-cleanup-logic centrally, in one place without going through the pains of manually editing each and every *.csproj file by hand every time you want to make an improvement.

Remove or uninstall library previously added : cocoapods

Remove pod name from Podfile then Open Terminal, set project folder path and Run pod update command.

NOTE: pod update will update all the libraries to the latest version and will also remove those libraries whose name have been removed from podfile.

#1214 - The used table type doesn't support FULLTEXT indexes

From official reference

Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.

https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html

InnoDB with MySQL 5.5 does not support Full-text indexes.

Java JTextField with input hint

You could create your own:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {

  public static void main(String[] args) {

    final JFrame frame = new JFrame();

    frame.setLayout(new BorderLayout());

    final JTextField textFieldA = new HintTextField("A hint here");
    final JTextField textFieldB = new HintTextField("Another hint here");

    frame.add(textFieldA, BorderLayout.NORTH);
    frame.add(textFieldB, BorderLayout.CENTER);
    JButton btnGetText = new JButton("Get text");

    btnGetText.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String message = String.format("textFieldA='%s', textFieldB='%s'",
            textFieldA.getText(), textFieldB.getText());
        JOptionPane.showMessageDialog(frame, message);
      }
    });

    frame.add(btnGetText, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.pack();
  }
}

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

'python3' is not recognized as an internal or external command, operable program or batch file

Python3.exe is not defined in windows

Specify the path for required version of python when you need to used it by creating virtual environment for your project

Python 3

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

Python2

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

then activate the environment using

.\environment\Scripts\activate.ps1

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

How to get cookie's expire time

You can set your cookie value containing expiry and get your expiry from cookie value.

// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);

// get
if (isset($_COOKIE["mycookie"])) {
  list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}

// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee

Hidden Features of Xcode

If you have a multi-touch capable Mac - use MultiClutch to map some of the keystrokes described by mouse gestures.

I use three finger forward and back to go forward and back in file history (cmd-alt-.), and pinch to switch between .h and .m.

Percentage width in a RelativeLayout

You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.

Subclass of RelativeLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with "Percent" suffix.

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
  <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_widthPercent="50%"
      app:layout_heightPercent="50%"
      app:layout_marginTopPercent="25%"
      app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

To use, you need to add this library to your Gradle dependency list:

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

Java :Add scroll into text area

Try adding these two lines to your code. I hope it will work. It worked for me :)

display.setLineWrap(true);
display.setWrapStyleWord(true);

Picture of output is shown below

enter image description here

How to send a JSON object over Request with Android?

Now since the HttpClient is deprecated the current working code is to use the HttpUrlConnection to create the connection and write the and read from the connection. But I preferred to use the Volley. This library is from android AOSP. I found very easy to use to make JsonObjectRequest or JsonArrayRequest

Server.Transfer Vs. Response.Redirect

Response.Redirect involves an extra round trip and updates the address bar.

Server.Transfer does not cause the address bar to change, the server responds to the request with content from another page

e.g.

Response.Redirect:-

  1. On the client the browser requests a page http://InitiallyRequestedPage.aspx
  2. On the server responds to the request with 302 passing the redirect address http://AnotherPage.aspx.
  3. On the client the browser makes a second request to the address http://AnotherPage.aspx.
  4. On the server responds with content from http://AnotherPage.aspx

Server.Transfer:-

  1. On the client browser requests a page http://InitiallyRequestedPage.aspx
  2. On the server Server.Transfer to http://AnotherPage.aspx
  3. On the server the response is made to the request for http://InitiallyRequestedPage.aspx passing back content from http://AnotherPage.aspx

Response.Redirect

Pros:- RESTful - It changes the address bar, the address can be used to record changes of state inbetween requests.

Cons:- Slow - There is an extra round-trip between the client and server. This can be expensive when there is substantial latency between the client and the server.

Server.Transfer

Pros:- Quick.

Cons:- State lost - If you're using Server.Transfer to change the state of the application in response to post backs, if the page is then reloaded that state will be lost, as the address bar will be the same as it was on the first request.

What is a "slug" in Django?

Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

Slug can create using SlugField

Ex:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

If you want to use title as slug, django has a simple function called slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

If it needs uniqueness, add unique=True in slug field.

for instance, from the previous example:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug

Converting VS2012 Solution to VS2010

Open the project file and not the solution. The project will be converted by the Wizard, and after converted, when you build the project, a new Solution will be generated as a VS2010 one.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my case, the TestTarget's compile sources were having files from the Main Target.

Ref:

Test Target contains files from main target in compile sources tab

Why this happens ?

  • This happens since we check the TestTarget association while creating the file

  • Or manually checking this option from the inspector.

    Ref:

    Create File - Test Target is Checked

How did i resolve ?

  • I removed the main target's files from compile source of Test Target

How to turn off caching on Firefox?

Have you tried to use CTRL-F5 to update the page?

How to use glob() to find files recursively?

Starting with Python 3.4, one can use the glob() method of one of the Path classes in the new pathlib module, which supports ** wildcards. For example:

from pathlib import Path

for file_path in Path('src').glob('**/*.c'):
    print(file_path) # do whatever you need with these files

Update: Starting with Python 3.5, the same syntax is also supported by glob.glob().

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

The configuration property is called hibernate.hbm2ddl.auto

In our development environment we set hibernate.hbm2ddl.auto=create-drop to drop and create a clean database each time we deploy, so that our database is in a known state.

In theory, you can set hibernate.hbm2ddl.auto=update to update your database with changes to your model, but I would not trust that on a production database. An earlier version of the documentation said that this was experimental, at least; I do not know the current status.

Therefore, for our production database, do not set hibernate.hbm2ddl.auto - the default is to make no database changes. Instead, we manually create an SQL DDL update script that applies changes from one version to the next.

How do I POST XML data with curl

You can try the following solution:

curl -v -X POST -d @payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"

Convert string to JSON Object

Without eval:

Your original string was not an actual string.

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

The easiest way to to wrap it all with a single quote.

 jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'

Then you can combine two steps to parse it to JSON:

 $.parseJSON(jsonObj.slice(1,-1))

How do I get list of methods in a Python class?

Python 3.x answer without external libraries

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded result:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

How to append a char to a std::string?

Try using the d as pointer y.append(*d)

Difference between StringBuilder and StringBuffer

Since StringBuffer is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow than StringBuilder.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

check the postgres server is running with following code

sudo service postgresql status

if the postgres server is inactive, write the following command.

sudo service postgresql start

Checking if type == list in python

This seems to work for me:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

how to kill hadoop jobs

Run list to show all the jobs, then use the jobID/applicationID in the appropriate command.

Kill mapred jobs:

mapred job -list
mapred job -kill <jobId>

Kill yarn jobs:

yarn application -list
yarn application -kill <ApplicationId>

How to convert a Java String to an ASCII byte array?

There is only one character wrong in the code you tried:

Charset characterSet = Charset.forName("US-ASCII");
String string = "Wazzup";
byte[] bytes = String.getBytes(characterSet);
               ^

Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:

byte[] bytes = string.getBytes(characterSet);

Function to check if a string is a date

If that's your whole string, then just try parsing it:

if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
  // it's a date
}

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

Programmatically close aspx page from code behind

You would typically do something like:

protected void btnClose_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}

However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window that wasn't opened by you (opened with window.open()).

IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.

In any case, you should be prepared to deal with the window not always closing!

One fix for the 2 above issues is to use:

protected void btnClose_Click(object sender, EventArgs e) {
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}

And create a close.html:

<html><head>
 <title></title>
 <script language="javascript" type="text/javascript">
     var redirectTimerId = 0;
     function closeWindow()
     {
         window.opener = top;
         redirectTimerId = window.setTimeout('redirect()', 2000);
         window.close(); 
     }

     function stopRedirect()
     {
         window.clearTimeout(redirectTimerId);
     }

     function redirect()
     {
         window.location = 'default.aspx';
     }
 </script>
 </head>
 <body onload="closeWindow()" onunload="stopRedirect()" style="">
     <center><h1>Please Wait...</h1></center>
 </body></html>

Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.

Edit line thickness of CSS 'underline' attribute

Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.

_x000D_
_x000D_
<span style="font-size:1em;text-decoration:underline;">_x000D_
 <span style="font-size:1.5em;">_x000D_
   Text with big font size and thin underline_x000D_
 </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Copying text outside of Vim with set mouse=a enabled

Holding shift while copying and pasting with selection worked for me

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

SQL Server: SELECT only the rows with MAX(DATE)

This works for me. use MAX(CONVERT(date, ReportDate)) to make sure you have date value

select max( CONVERT(date, ReportDate)) FROM [TraxHistory]

wp-admin shows blank page, how to fix it?

After dozens of times trying to fix this problem reading forums and posts, reinstalling WordPress, removing white spaces, putting lines of code in wp-config.php, index.php, admin.php, I fixed the issue just by renaming the plugins folder to "pluginss" in FTP. So wordpress asked me to update the database. I updated and I could enter at /wp-admin. A plugin was causing some conflict, so when I rename the plugins folder, all plugins automatically has been disabled.

As I was inside the /wp-admin dashboard, I could rename the "pluginss" folder to the regular name and start to activate all the plugins one by one and see what plugin was broken.

Now is 100% fine.

Set IDENTITY_INSERT ON is not working

You might be just missing the column list, as the message says

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON

INSERT INTO [MyDB].[dbo].[Equipment]
            (COL1,
             COL2)
SELECT COL1,
       COL2
FROM   [MyDBQA].[dbo].[Equipment]

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

List to array conversion to use ravel() function

Use the following code:

import numpy as np

myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array
print(myArray)

WP -- Get posts by category?

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>

How can I use threading in Python?

NOTE: For actual parallelization in Python, you should use the multiprocessing module to fork multiple processes that execute in parallel (due to the global interpreter lock, Python threads provide interleaving, but they are in fact executed serially, not in parallel, and are only useful when interleaving I/O operations).

However, if you are merely looking for interleaving (or are doing I/O operations that can be parallelized despite the global interpreter lock), then the threading module is the place to start. As a really simple example, let's consider the problem of summing a large range by summing subranges in parallel:

import threading

class SummingThread(threading.Thread):
     def __init__(self,low,high):
         super(SummingThread, self).__init__()
         self.low=low
         self.high=high
         self.total=0

     def run(self):
         for i in range(self.low,self.high):
             self.total+=i


thread1 = SummingThread(0,500000)
thread2 = SummingThread(500000,1000000)
thread1.start() # This actually causes the thread to run
thread2.start()
thread1.join()  # This waits until the thread has completed
thread2.join()
# At this point, both threads have completed
result = thread1.total + thread2.total
print result

Note that the above is a very stupid example, as it does absolutely no I/O and will be executed serially albeit interleaved (with the added overhead of context switching) in CPython due to the global interpreter lock.

php random x digit number

The following code generates a 4 digits random number:

echo sprintf( "%04d", rand(0,9999));

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Java string to date conversion

That's the hard way, and those java.util.Date setter methods have been deprecated since Java 1.1 (1997). Simply format the date using SimpleDateFormat using a format pattern matching the input string.

In your specific case of "January 2, 2010" as the input string:

  1. "January" is the full text month, so use the MMMM pattern for it
  2. "2" is the short day-of-month, so use the d pattern for it.
  3. "2010" is the 4-digit year, so use the yyyy pattern for it.
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010

Note the importance of the explicit Locale argument. If you omit it, then it will use the default locale which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a java.text.ParseException even though when the format pattern seems valid.

Here's an extract of relevance from the javadoc, listing all available format patterns:

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M/L Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. MMMMM or more is unnecessary.

Here are some examples of valid SimpleDateFormat patterns to parse a given string to date:

Input string Pattern
2001.07.04 AD at 12:08:56 PDT yyyy.MM.dd G 'at' HH:mm:ss z
Wed, Jul 4, '01 EEE, MMM d, ''yy
12:08 PM h:mm a
12 o'clock PM, Pacific Daylight Time hh 'o''clock' a, zzzz
0:08 PM, PDT K:mm a, z
02001.July.04 AD 12:08 PM yyyyy.MMMM.dd GGG hh:mm aaa
Wed, 4 Jul 2001 12:08:56 -0700 EEE, d MMM yyyy HH:mm:ss Z
010704120856-0700 yyMMddHHmmssZ
2001-07-04T12:08:56.235-0700 yyyy-MM-dd'T'HH:mm:ss.SSSZ
2001-07-04T12:08:56.235-07:00 yyyy-MM-dd'T'HH:mm:ss.SSSXXX
2001-W27-3 YYYY-'W'ww-u

An important note is that SimpleDateFormat is not thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope.


Java 8 update

If you happen to be on Java 8 or newer, then use DateTimeFormatter (also here, click the link to see all predefined formatters and available format patterns; the tutorial is available here). This new API is inspired by JodaTime.

String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter) instead of LocalDate#parse(text, formatter). And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter) instead.

Here's an extract of relevance from the javadoc, listing all available format patterns:

Symbol Meaning Presentation Examples
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;

Do note that it has several predefined formatters for the more popular patterns. So instead of e.g. DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);, you could use DateTimeFormatter.RFC_1123_DATE_TIME. This is possible because they are, on the contrary to SimpleDateFormat, thread safe. You could thus also define your own, if necessary.

For a particular input string format, you don't need to use an explicit DateTimeFormatter: a standard ISO 8601 date, like 2016-09-26T17:44:57Z, can be parsed directly with LocalDateTime#parse(text) as it already uses the ISO_LOCAL_DATE_TIME formatter. Similarly, LocalDate#parse(text) parses an ISO date without the time component (see ISO_LOCAL_DATE), and ZonedDateTime#parse(text) parses an ISO date with an offset and time zone added (see ISO_ZONED_DATE_TIME).

How do I change Eclipse to use spaces instead of tabs?

In Eclipse go to Window » Preferences then search for Formatter.

You will see various bold links, click on each bold link and set it to use spaces instead of tabs.

In the java formatter link, you have to edit the profile and select the tab policy, spaces only in indentation tab

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

How to view method information in Android Studio?

Yes, you can. Go to File -> Settings -> Editor -> Show quick documentation on mouse move

Or, in Mac OS X, go to Android Studio - > Preferences -> Editor - > General > Show quick documentation on mouse move.

How to subtract hours from a date in Oracle so it affects the day also

sysdate-(2/11)

A day consists of 24 hours. So, to subtract 2 hours from a day you need to divide it by 24:

DATE_value - 2/24

Using interval for the same:

DATE_value - interval '2' hour

How can I render repeating React elements?

In the spirit of functional programming, let's make our components a bit easier to work with by using abstractions.

// converts components into mappable functions
var mappable = function(component){
  return function(x, i){
    return component({key: i}, x);
  }
}

// maps on 2-dimensional arrays
var map2d = function(m1, m2, xss){
  return xss.map(function(xs, i, arr){
    return m1(xs.map(m2), i, arr);
  });
}

var td = mappable(React.DOM.td);
var tr = mappable(React.DOM.tr);
var th = mappable(React.DOM.th);

Now we can define our render like this:

render: function(){
  return (
    <table>
      <thead>{this.props.titles.map(th)}</thead>
      <tbody>{map2d(tr, td, this.props.rows)}</tbody>
    </table>
  );
}

jsbin


An alternative to our map2d would be a curried map function, but people tend to shy away from currying.

Is it possible to format an HTML tooltip (title attribute)?

No. But there are other options out there like Overlib, and jQuery that allow you this freedom.

Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).

SQL How to remove duplicates within select query?

here is the solution for your query returning only one row for each date in that table here in the solution 'tony' will occur twice as two different start dates are there for it

SELECT * FROM 
(
    SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC )  RNM
    FROM TABLE T1
)
WHERE RNM=1

What is your favorite C programming trick?

Here is an example how to make C code completly unaware about what is actually used of HW for running the app. The main.c does the setup and then the free layer can be implemented on any compiler/arch. I think it is quite neat for abstracting C code a bit, so it does not get to be to spesific.

Adding a complete compilable example here.

/* free.h */
#ifndef _FREE_H_
#define _FREE_H_
#include <stdio.h>
#include <string.h>
typedef unsigned char ubyte;

typedef void (*F_ParameterlessFunction)() ;
typedef void (*F_CommandFunction)(ubyte byte) ;

void F_SetupLowerLayer (
F_ParameterlessFunction initRequest,
F_CommandFunction sending_command,
F_CommandFunction *receiving_command);
#endif

/* free.c */
static F_ParameterlessFunction Init_Lower_Layer = NULL;
static F_CommandFunction Send_Command = NULL;
static ubyte init = 0;
void recieve_value(ubyte my_input)
{
    if(init == 0)
    {
        Init_Lower_Layer();
        init = 1;
    }
    printf("Receiving 0x%02x\n",my_input);
    Send_Command(++my_input);
}

void F_SetupLowerLayer (
    F_ParameterlessFunction initRequest,
    F_CommandFunction sending_command,
    F_CommandFunction *receiving_command)
{
    Init_Lower_Layer = initRequest;
    Send_Command = sending_command;
    *receiving_command = &recieve_value;
}

/* main.c */
int my_hw_do_init()
{
    printf("Doing HW init\n");
    return 0;
}
int my_hw_do_sending(ubyte send_this)
{
    printf("doing HW sending 0x%02x\n",send_this);
    return 0;
}
F_CommandFunction my_hw_send_to_read = NULL;

int main (void)
{
    ubyte rx = 0x40;
    F_SetupLowerLayer(my_hw_do_init,my_hw_do_sending,&my_hw_send_to_read);

    my_hw_send_to_read(rx);
    getchar();
    return 0;
}

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Find all tables containing column with specified name - MS SQL Server

Search Tables:

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%MyName%'
ORDER BY    TableName
            ,ColumnName;

Search Tables and Views:

SELECT      COLUMN_NAME AS 'ColumnName'
            ,TABLE_NAME AS  'TableName'
FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%MyName%'
ORDER BY    TableName
            ,ColumnName;

How to append elements at the end of ArrayList in Java?

import java.util.*;


public class matrixcecil {
    public static void main(String args[]){
        List<Integer> k1=new ArrayList<Integer>(10);
        k1.add(23);
        k1.add(10);
        k1.add(20);
        k1.add(24);
        int i=0;
        while(k1.size()<10){
            if(i==(k1.get(k1.size()-1))){

            }
             i=k1.get(k1.size()-1);
             k1.add(30);
             i++;
             break;
        }
        System.out.println(k1);
    }

}

I think this example will help you for better solution.

Elegant way to report missing values in a data.frame

For one more graphical solution, visdat package offers vis_miss.

library(visdat)
vis_miss(airquality)

enter image description here

Very similar to Amelia output with a small difference of giving %s on missings out of the box.

Getting a union of two arrays in JavaScript

I would first concatenate the arrays, then I would return only the unique value.

You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array.

In your case with arrays array1 and array2 it would look like this:

  1. array1.concat(array2) - concatenate the two arrays
  2. array1.concat(array2).unique() - return only the unique values. Here unique() is a method you added to the prototype for Array.

The whole thing would look like this:

_x000D_
_x000D_
Array.prototype.unique = function () {_x000D_
    var r = new Array();_x000D_
    o: for(var i = 0, n = this.length; i < n; i++)_x000D_
    {_x000D_
        for(var x = 0, y = r.length; x < y; x++)_x000D_
        {_x000D_
            if(r[x]==this[i])_x000D_
            {_x000D_
                continue o;_x000D_
            }_x000D_
        }_x000D_
        r[r.length] = this[i];_x000D_
    }_x000D_
    return r;_x000D_
}_x000D_
var array1 = [34,35,45,48,49];_x000D_
var array2 = [34,35,45,48,49,55];_x000D_
_x000D_
// concatenate the arrays then return only the unique values_x000D_
console.log(array1.concat(array2).unique());
_x000D_
_x000D_
_x000D_

How to set null to a GUID property

Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff") but that's a lot uglier IMHO.

Determine the process pid listening on a certain port

netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils) as with pipe:

pid=`fuser $PORT/tcp`

it prints pure pid so you can drop sed magic out.

One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):

$ fuser -k $port/tcp       # with SIGKILL
$ fuser -k -15 $port/tcp   # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM

Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser

C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

How to edit Docker container files from the host?

Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can.

Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do:

$ docker run --name="test" -v /volume-test debian echo "test"

The directory /volume-test inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with:

$ docker inspect -f "{{.Volumes}}" test
map[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895]

If you really need to just make a quick edit to a file to test something, either use docker exec to get a shell in the container and edit directly, or use docker cp to copy the file out, edit on the host and copy back in.

How to get just numeric part of CSS property with jQuery?

parseint will truncate any decimal values (e.g. 1.5em gives 1).

Try a replace function with regex e.g.

$this.css('marginBottom').replace(/([\d.]+)(px|pt|em|%)/,'$1');

How do I get the collection of Model State Errors in ASP.NET MVC?

Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.

    <%= Html.ShowAllErrors(mykey) %>

HtmlHelper:

    public static String ShowAllErrors(this HtmlHelper helper, String key) {
        StringBuilder sb = new StringBuilder();
        if (helper.ViewData.ModelState[key] != null) {
            foreach (var e in helper.ViewData.ModelState[key].Errors) {
                TagBuilder div = new TagBuilder("div");
                div.MergeAttribute("class", "field-validation-error");
                div.SetInnerText(e.ErrorMessage);
                sb.Append(div.ToString());
            }
        }
        return sb.ToString();
    }

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Maximum packet size for a TCP connection

One solution can be to set socket option TCP_MAXSEG (http://linux.die.net/man/7/tcp) to a value that is "safe" with underlying network (e.g. set to 1400 to be safe on ethernet) and then use a large buffer in send system call. This way there can be less system calls which are expensive. Kernel will split the data to match MSS.

This way you can avoid truncated data and your application doesn't have to worry about small buffers.

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

Tomcat is web server or application server?

Tomcat is a web server (can handle HTTP requests/responses) and web container (implements Java Servlet API, also called servletcontainer) in one. Some may call it an application server, but it is definitely not an fullfledged Java EE application server (it does not implement the whole Java EE API).

See also:

Fastest way to copy a file in Node.js

You can do it using the fs-extra module very easily:

const fse = require('fs-extra');

let srcDir = 'path/to/file';
let destDir = 'pat/to/destination/directory';

fse.moveSync(srcDir, destDir, function (err) {

    // To move a file permanently from a directory
    if (err) {
        console.error(err);
    } else {
        console.log("success!");
    }
});

Or

fse.copySync(srcDir, destDir, function (err) {

     // To copy a file from a directory
     if (err) {
         console.error(err);
     } else {
         console.log("success!");
     }
});

How can I select records ONLY from yesterday?

to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')