Programs & Examples On #Bounding

Can't perform a React state update on an unmounted component

The solution from @ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:

  1. Essential packages
"dependencies": 
{
  "react": "17.0.1",
}
"devDependencies": { 
  "typescript": "4.1.5",
}

  1. My Hook Component
export const SubscriptionsView: React.FC = () => {
  const [data, setData] = useState<Subscription[]>();
  const isMounted = React.useRef(true);

  React.useEffect(() => {
    if (isMounted.current) {
      // fetch data
      // setData (fetch result)

      return () => {
        isMounted.current = false;
      };
    }
  }
});

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Figure out size of UILabel based on String in Swift

This is my answer in Swift 4.1 and Xcode 9.4.1

//This is your label
let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
proNameLbl.text = "This is your text"
proNameLbl.font = UIFont.systemFont(ofSize: 17)
proNameLbl.numberOfLines = 0
proNameLbl.lineBreakMode = .byWordWrapping
infoView.addSubview(proNameLbl)

//Function to calculate height for label based on text
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

Now you call this function

//Call this function
let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
print(height)//Output : 41.0

Extracting text OpenCV

Here is an alternative approach that I used to detect the text blocks:

  1. Converted the image to grayscale
  2. Applied threshold (simple binary threshold, with a handpicked value of 150 as the threshold value)
  3. Applied dilation to thicken lines in image, leading to more compact objects and less white space fragments. Used a high value for number of iterations, so dilation is very heavy (13 iterations, also handpicked for optimal results).
  4. Identified contours of objects in resulted image using opencv findContours function.
  5. Drew a bounding box (rectangle) circumscribing each contoured object - each of them frames a block of text.
  6. Optionally discarded areas that are unlikely to be the object you are searching for (e.g. text blocks) given their size, as the algorithm above can also find intersecting or nested objects (like the entire top area for the first card) some of which could be uninteresting for your purposes.

Below is the code written in python with pyopencv, it should easy to port to C++.

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image) 

The original image is the first image in your post.

After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:

Dilated image

Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:

enter image description here

You can see the text block on the left is detected as a separate block, delimited from its surroundings.

Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:

enter image description here

enter image description here

Tuning the parameters

The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.

For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.

Finding other object types:

For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):

enter image description here

Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

Matplotlib 2 Subplots, 1 Colorbar

As pointed out in other answers, the idea is usually to define an axes for the colorbar to reside in. There are various ways of doing so; one that hasn't been mentionned yet would be to directly specify the colorbar axes at subplot creation with plt.subplots(). The advantage is that the axes position does not need to be manually set and in all cases with automatic aspect the colorbar will be exactly the same height as the subplots. Even in many cases where images are used the result will be satisfying as shown below.

When using plt.subplots(), the use of gridspec_kw argument allows to make the colorbar axes much smaller than the other axes.

fig, (ax, ax2, cax) = plt.subplots(ncols=3,figsize=(5.5,3), 
                  gridspec_kw={"width_ratios":[1,1, 0.05]})

Example:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, ax2, cax) = plt.subplots(ncols=3,figsize=(5.5,3), 
                  gridspec_kw={"width_ratios":[1,1, 0.05]})
fig.subplots_adjust(wspace=0.3)
im  = ax.imshow(np.random.rand(11,8), vmin=0, vmax=1)
im2 = ax2.imshow(np.random.rand(11,8), vmin=0, vmax=1)
ax.set_ylabel("y label")

fig.colorbar(im, cax=cax)

plt.show()

enter image description here

This works well, if the plots' aspect is autoscaled or the images are shrunk due to their aspect in the width direction (as in the above). If, however, the images are wider then high, the result would look as follows, which might be undesired.

enter image description here

A solution to fix the colorbar height to the subplot height would be to use mpl_toolkits.axes_grid1.inset_locator.InsetPosition to set the colorbar axes relative to the image subplot axes.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, (ax, ax2, cax) = plt.subplots(ncols=3,figsize=(7,3), 
                  gridspec_kw={"width_ratios":[1,1, 0.05]})
fig.subplots_adjust(wspace=0.3)
im  = ax.imshow(np.random.rand(11,16), vmin=0, vmax=1)
im2 = ax2.imshow(np.random.rand(11,16), vmin=0, vmax=1)
ax.set_ylabel("y label")

ip = InsetPosition(ax2, [1.05,0,0.05,1]) 
cax.set_axes_locator(ip)

fig.colorbar(im, cax=cax, ax=[ax,ax2])

plt.show()

enter image description here

boundingRectWithSize for NSAttributedString returning wrong size

I had the same problem, but I recognised that height constrained has been set correctly. So I did the following:

-(CGSize)MaxHeighForTextInRow:(NSString *)RowText width:(float)UITextviewWidth {

    CGSize constrainedSize = CGSizeMake(UITextviewWidth, CGFLOAT_MAX);

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
                                          nil];

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:RowText attributes:attributesDictionary];

    CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    if (requiredHeight.size.width > UITextviewWidth) {
        requiredHeight = CGRectMake(0, 0, UITextviewWidth, requiredHeight.size.height);
    }

    return requiredHeight.size;
}

Scale image to fit a bounding box

Are you looking to scale upwards but not downwards?

div {
    border: solid 1px green;
    width: 60px;
    height: 70px;
}

div img {
    width: 100%;
    height: 100%;
    min-height: 500px;
    min-width: 500px;
    outline: solid 1px red;
}

This however, does not lock aspect-ratio.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

What you need is a quadrangle instead of a rotated rectangle. RotatedRect will give you incorrect results. Also you will need a perspective projection.

Basicly what must been done is:

  • Loop through all polygon segments and connect those which are almost equel.
  • Sort them so you have the 4 most largest line segments.
  • Intersect those lines and you have the 4 most likely corner points.
  • Transform the matrix over the perspective gathered from the corner points and the aspect ratio of the known object.

I implemented a class Quadrangle which takes care of contour to quadrangle conversion and will also transform it over the right perspective.

See a working implementation here: Java OpenCV deskewing a contour

Underline text in UIlabel

Based on Kovpas & Damien Praca's Answers, here is an implementation of UILabelUnderligned which also support textAlignemnt.

#import <UIKit/UIKit.h>

@interface UILabelUnderlined : UILabel

@end

and the implementation:

#import "UILabelUnderlined.h"

@implementation DKUILabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

    CGContextSetLineWidth(ctx, 1.0f);

    CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];

    // handle textAlignement

    int alignementXOffset = 0;

    switch (self.textAlignment) {
        case UITextAlignmentLeft:
            break;
        case UITextAlignmentCenter:
            alignementXOffset = (self.frame.size.width - textSize.width)/2;
            break;
        case UITextAlignmentRight:
            alignementXOffset = self.frame.size.width - textSize.width;
            break;
    }

    CGContextMoveToPoint(ctx, alignementXOffset, self.bounds.size.height - 1);
    CGContextAddLineToPoint(ctx, alignementXOffset+textSize.width, self.bounds.size.height - 1);

    CGContextStrokePath(ctx);

    [super drawRect:rect];  
}


@end

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Well, it's fairly self-explanatory: you've run out of memory.

You may want to try starting it with more memory, using the -Xmx flag, e.g.

java -Xmx2048m [whatever you'd have written before]

This will use up to 2 gigs of memory.

See the non-standard options list for more details.

How can I mix LaTeX in with Markdown?

What language are you using?

If you can use ruby, then maruku can be configured to process maths using various latex->MathML converters. Instiki uses this. It's also possible to extend PHPMarkdown to use itex2MML as well to convert maths. Basically, you insert extra steps in the Markdown engine at the appropriate points.

So with ruby and PHP, this is done. I guess these solutions could also be adapted to other languages - I've gotten the itex2MML extension to produce perl bindings as well.

Styling an anchor tag to look like a submit button

I Suggest you to use both Input Submit / Button instead of anchor and put this line of code onClick="javascript:location.href = 'http://stackoverflow.com';" in that Input Submit / Button which you want to work as link.

Submit Example

<input type="submit" value="Submit" onClick="javascript:location.href = 'some_url';" />

Button Example

<button type="button" onClick="javascript:location.href = 'some_url';" />Submit</button>

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

Error including image in Latex

I had the same problem, caused by a clash between the graphicx package and an inclusion of the epsfig package that survived the ages...

Please check that there is no inclusion of epsfig, it is deprecated.

How to calculate the bounding box for a given lat/lng location?

Thanks @Fedrico A. for the Phyton implementation, I have ported it into a Objective C category class. Here is:

#import "LocationService+Bounds.h"

//Semi-axes of WGS-84 geoidal reference
const double WGS84_a = 6378137.0; //Major semiaxis [m]
const double WGS84_b = 6356752.3; //Minor semiaxis [m]

@implementation LocationService (Bounds)

struct BoundsLocation {
    double maxLatitude;
    double minLatitude;
    double maxLongitude;
    double minLongitude;
};

+ (struct BoundsLocation)locationBoundsWithLatitude:(double)aLatitude longitude:(double)aLongitude maxDistanceKm:(NSInteger)aMaxKmDistance {
    return [self boundingBoxWithLatitude:aLatitude longitude:aLongitude halfDistanceKm:aMaxKmDistance/2];
}

#pragma mark - Algorithm 

+ (struct BoundsLocation)boundingBoxWithLatitude:(double)aLatitude longitude:(double)aLongitude halfDistanceKm:(double)aDistanceKm {
    double radianLatitude = [self degreesToRadians:aLatitude];
    double radianLongitude = [self degreesToRadians:aLongitude];
    double halfDistanceMeters = aDistanceKm*1000;


    double earthRadius = [self earthRadiusAtLatitude:radianLatitude];
    double parallelRadius = earthRadius*cosl(radianLatitude);

    double radianMinLatitude = radianLatitude - halfDistanceMeters/earthRadius;
    double radianMaxLatitude = radianLatitude + halfDistanceMeters/earthRadius;
    double radianMinLongitude = radianLongitude - halfDistanceMeters/parallelRadius;
    double radianMaxLongitude = radianLongitude + halfDistanceMeters/parallelRadius;

    struct BoundsLocation bounds;
    bounds.minLatitude = [self radiansToDegrees:radianMinLatitude];
    bounds.maxLatitude = [self radiansToDegrees:radianMaxLatitude];
    bounds.minLongitude = [self radiansToDegrees:radianMinLongitude];
    bounds.maxLongitude = [self radiansToDegrees:radianMaxLongitude];

    return bounds;
}

+ (double)earthRadiusAtLatitude:(double)aRadianLatitude {
    double An = WGS84_a * WGS84_a * cosl(aRadianLatitude);
    double Bn = WGS84_b * WGS84_b * sinl(aRadianLatitude);
    double Ad = WGS84_a * cosl(aRadianLatitude);
    double Bd = WGS84_b * sinl(aRadianLatitude);
    return sqrtl( ((An * An) + (Bn * Bn))/((Ad * Ad) + (Bd * Bd)) );
}

+ (double)degreesToRadians:(double)aDegrees {
    return M_PI*aDegrees/180.0;
}

+ (double)radiansToDegrees:(double)aRadians {
    return 180.0*aRadians/M_PI;
}



@end

I have tested it and seems be working nice. Struct BoundsLocation should be replaced by a class, I have used it just to share it here.

How can I make an EXE file from a Python program?

py2exe:

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

jquery find closest previous sibling with class

I think all the answers are lacking something. I prefer using something like this

$('li.current_sub').prevUntil("li.par_cat").prev();

Saves you not adding :first inside the selector and is easier to read and understand. prevUntil() method has a better performance as well rather than using prevAll()

How do I change the JAVA_HOME for ant?

java_home always points to the jdk, the compiler that gave you the classes, and the jre is thw way that your browser or whatever will the compiled classes so it must have matching between jdk and jre in the version.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

Register .NET Framework 4.5 in IIS 7.5

For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45 As administrative command prompt.

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

How to insert image in mysql database(table)?

Please try below code

INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('E:/Images/jack.jpg'));

Simplest way to download and unzip files in Node.js cross-platform?

I tried a few of the nodejs unzip libraries including adm-zip and unzip, then settled on extract-zip which is a wrapper around yauzl. Seemed the simplest to implement.

https://www.npmjs.com/package/extract-zip

var extract = require('extract-zip')
extract(zipfile, { dir: outputPath }, function (err) {
   // handle err
})

Auto select file in Solution Explorer from its open tab

In Visual Studio 2012, the same can be done using the "Sync With Active Document" option in Solution Explorer

Struct with template variables in C++

The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")

In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.

Do it like Andrey shows.

The specified child already has a parent. You must call removeView() on the child's parent first

Try this way,hope this will help you to solve your problem.

TextView textView = new TextView(this);
textView.setText("CustomTextView");
addContentView(textView,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

Is there a color code for transparent in HTML?

Yeah I think the best way to transparent the background colour (make opacity only for the background) is using

.style{
        background-color: rgba(100, 100, 100, 0.5);
}

Above statement 0.5 is the opacity value.

It only apply the opacity changes to the background colour (not all elements')

The "opacity" attribute in the CSS will transparent all the elements in the block.

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How do I select an entire row which has the largest ID in the table?

You can not give order by because order by does a "full scan" on a table.

The following query is better:

SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);

IPython Notebook save location

To add to Victor's answer, I was able to change the save directory on Windows using...

c.NotebookApp.notebook_dir = 'C:\\Users\\User\\Folder'

How do I run two commands in one line in Windows CMD?

With windows 10 you can also use scriptrunner:

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror

it allows you to start few commands on one line you want you can run them consecutive or without waiting each other, you can put timeouts and rollback on error.

Does mobile Google Chrome support browser extensions?

Extensions are not supported, see: https://developers.google.com/chrome/mobile/docs/faq .

Specifically:

Does Chrome for Android now support the embedded WebView for a hybrid native/web app?

A Chrome-based WebView is included in Android 4.4 (KitKat) and later. See the WebView overview for details.

Does Chrome for Android support apps and extensions?

Chrome apps and extensions are currently not supported on Chrome for Android. We have no plans to announce at this time.

Can I write and deploy web apps on Chrome for Android?

Though Chrome apps are not currently supported, we would love to see great interactive web sites accessible by URL.

How to call VS Code Editor from terminal / command line

In a way I am reticent to add to the long list of answers. However, I searched this page for the word "portable" and came up empty. (And I did a full Stack Overflow search and also found nothing.) So I want to add this very specific answer for potential future searchers.

This answer is for if you installed VS Code in Portable Mode on Windows 10.

"Portable Mode" refers to what is described on the official VS Code web pages, which as of 21 January 2021 are found here: https://code.visualstudio.com. It does not mean the Visual Studio Code Portable project started/run by Gareth Flowers, or any similar project. (I am not saying anything bad about this or other projects - I have neither used nor evaluated.) If you are using one of those projects, you need to check with that project documentation/community - although this might work.

"Installing" VS Code in Portable Mode is downloading a .zip archive and extracting it locally wherever you want your VS Code "installation" to live. There is no actual installation or setup that is run, so there is no automatic adding of the code command to your PATH.


Answer

After extracting the Portable Mode VS Code files to the location of your choice, there should be a bin folder in that location. Copy the full path of that bin folder and add it to your System or User (your choice) PATH variable.

You should then be able to use the code command from PowerShell or CMD.

What is the meaning of the word logits in TensorFlow?

The logit (/'lo?d??t/ LOH-jit) function is the inverse of the sigmoidal "logistic" function or logistic transform used in mathematics, especially in statistics. When the function's variable represents a probability p, the logit function gives the log-odds, or the logarithm of the odds p/(1 - p).

See here: https://en.wikipedia.org/wiki/Logit

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Xcode 10.2 and Swift 5 and above

DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
   // code to execute                 
})

Microsoft Azure: How to create sub directory in a blob container

To add on to what Egon said, simply create your blob called "folder/1.txt", and it will work. No need to create a directory.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Laravel Eloquent LEFT JOIN WHERE NULL

I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.

You should be able to do that with the following code:

$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
die();

Hopefully that should give you enough information to allow you to figure out what's gone wrong.

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

How to programmatically modify WCF app.config endpoint address setting?

MyServiceClient client = new MyServiceClient(binding, endpoint);
client.Endpoint.Address = new EndpointAddress("net.tcp://localhost/webSrvHost/service.svc");
client.Endpoint.Binding = new NetTcpBinding()
            {
                Name = "yourTcpBindConfig",
                ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                ListenBacklog = 40 }

It's very easy to modify the uri in config or binding info in config. Is this what you want?

Replace all spaces in a string with '+'

You need the /g (global) option, like this:

var replaced = str.replace(/ /g, '+');

You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

Hex transparency in colors

try this on google search (or click here)

255 * .2 to hex

it will generate 0x33 as a result.

However, google does not round off values so you can only use 1-digit multipliers. if you want to use say .85, you have to get the rounded-off value of 255 * .85 first, then type (rounded-value here) to hex in google search.

How can I process each letter of text using Javascript?

One more solution...

var strg= 'This is my string';
for(indx in strg){
  alert(strg[indx]);
}

initialize a numpy array

Introduced in numpy 1.8:

numpy.full

Return a new array of given shape and type, filled with fill_value.

Examples:

>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

Convert List into Comma-Separated String

If you have a collection of ints:

List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };  

You can use string.Join to get a string:

var result = String.Join(",", customerIds);

Enjoy!

Adding Image to xCode by dragging it from File

For xCode 10, first you need to add the image in your assetsCatalogue and then type this:

let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))

For beginners, let imageView is the name of the UIImageView object we are about to create.

An example for embedding an image into a viewControler file would look like this:

import UIKit

class TutorialViewCotroller: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
        view.addSubview(imageView)
    }
}

Please notice that I did not use any extension for the image file name, as in my case it is a group of images.

HTML "overlay" which allows clicks to fall through to elements behind it

Generally, this isn't a great idea. Taking your scenario, if you had evil intentions, you could hide everything underneath your "overlay". Then, when a user clicks on a link they think should take them to bankofamerica.com, instead it triggers the hidden link which takes them to myevilsite.com.

That said, event bubbling works, and if it's within an application, it's not a big deal. The following code is an example. Clicking the blue area pops up an alert, even though the alert is set on the red area. Note that the orange area does NOT work, because the event will propagate through the PARENT elements, so your overlay needs to be inside whatever element you're observing the clicks on. In your scenario, you may be out of luck.

<html>
<head>
</head>
<body>
    <div id="outer" style="position:absolute;height:50px;width:60px;z-index:1;background-color:red;top:5px;left:5px;" onclick="alert('outer')"> 
        <div id="nested" style="position:absolute;height:50px;width:60px;z-index:2;background-color:blue;top:15px;left:15px;">
        </div>
    </div>
    <div id="separate" style="position:absolute;height:50px;width:60px;z-index:3;background-color:orange;top:25px;left:25px;">
    </div>
</body>
</html>

jsPDF multi page PDF with HTML renderer

$( document ).ready(function() {    
$('#cmd').click(function() {
      var options = {
              pagesplit: true //include this in your code
      };
      var pdf = new jsPDF('p', 'pt', 'a4');
      pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
        pdf.save('Menu.pdf');
      });
    });
});

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Internal vs. Private Access Modifiers

Find an explanation below. You can check this link for more details - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html

Private: - Private members are only accessible within the own type (Own class).

Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.

enter image description here

Reference :

dotnetbull - what is access modifier in c#

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.

JavaScript string encryption and decryption?

_x000D_
_x000D_
 var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");_x000D_
//U2FsdGVkX18ZUVvShFSES21qHsQEqZXMxQ9zgHy+bu0=_x000D_
_x000D_
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");_x000D_
//4d657373616765_x000D_
_x000D_
_x000D_
document.getElementById("demo1").innerHTML = encrypted;_x000D_
document.getElementById("demo2").innerHTML = decrypted;_x000D_
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
_x000D_
Full working sample actually is:_x000D_
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>_x000D_
_x000D_
<br><br>_x000D_
<label>encrypted</label>_x000D_
<div id="demo1"></div>_x000D_
<br>_x000D_
_x000D_
<label>decrypted</label>_x000D_
<div id="demo2"></div>_x000D_
_x000D_
<br>_x000D_
<label>Actual Message</label>_x000D_
<div id="demo3"></div>
_x000D_
_x000D_
_x000D_

How to convert a string or integer to binary in Ruby?

In ruby Integer class, to_s is defined to receive non required argument radix called base, pass 2 if you want to receive binary representation of a string.

Here is a link for an official documentation of String#to_s

  1.upto(10).each { |n|  puts n.to_s(2) }

Detecting an undefined object property

Also, the same things can be written shorter:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}

How to initialize var?

var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

So, no you are not allowed to do this.

When you say "some empty value"...if you mean:

var s = string.Empty;
//
var s = "";

Then yes, you may do that, but not null.

Does svn have a `revert-all` command?

To revert modified files:

sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

Get a specific bit from byte

This

public static bool GetBit(this byte b, int bitNumber) {
   return (b & (1 << bitNumber)) != 0;
}

should do it, I think.

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.

Example

git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop

Explanation

Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

How can I use pointers in Java?

There are pointers in Java, but you cannot manipulate them the way that you can in C++ or C. When you pass an object, you are passing a pointer to that object, but not in the same sense as in C++. That object cannot be dereferenced. If you set its values using its native accessors, it will change because Java knows its memory location through the pointer. But the pointer is immutable. When you attempt to set the pointer to a new location, you instead end up with a new local object with the same name as the other. The original object is unchanged. Here is a brief program to demonstrate the difference.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone {

    public static void main(String[] args) throws java.lang.Exception {
        System.out.println("Expected # = 0 1 2 2 1");
        Cat c = new Cat();
        c.setClaws(0);
        System.out.println("Initial value is " + c.getClaws());
        // prints 0 obviously
        clawsAreOne(c);
        System.out.println("Accessor changes value to " + c.getClaws());
        // prints 1 because the value 'referenced' by the 'pointer' is changed using an accessor.
        makeNewCat(c);
        System.out.println("Final value is " + c.getClaws());
        // prints 1 because the pointer is not changed to 'kitten'; that would be a reference pass.
    }

    public static void clawsAreOne(Cat kitty) {
        kitty.setClaws(1);
    }

    public static void makeNewCat(Cat kitty) {
        Cat kitten = new Cat();
        kitten.setClaws(2);
        kitty = kitten;
        System.out.println("Value in makeNewCat scope of kitten " + kitten.getClaws());
        //Prints 2. the value pointed to by 'kitten' is 2
        System.out.println("Value in makeNewcat scope of kitty " + kitty.getClaws());
        //Prints 2. The local copy is being used within the scope of this method.
    }
}

class Cat {

    private int claws;

    public void setClaws(int i) {
        claws = i;
    }

    public int getClaws() {
        return claws;
    }
}

This can be run at Ideone.com.

How to implement Android Pull-to-Refresh

Note there are UX issues to contend with when implementing on Android and WP.

"A great indicator for why designers/devs should not implement pull-to-refresh in the style iOS apps do is how Google and their teams never use pull-to-refresh on Android while they do use it in iOS. "

https://plus.google.com/109453683460749241197/posts/eqYxXR8L4eb

What is compiler, linker, loader?

  • A compiler reads, analyses and translates code into either an object file or a list of error messages.
  • A linker combines one or more object files and possible some library code into either some executable, some library or a list of error messages.
  • A loader reads the executable code into memory, does some address translation and tries to run the program resulting in a running program or an error message (or both).

ASCII representation:

[Source Code] ---> Compiler ---> [Object code] --*
                                                 |
[Source Code] ---> Compiler ---> [Object code] --*--> Linker --> [Executable] ---> Loader 
                                                 |                                    |
[Source Code] ---> Compiler ---> [Object code] --*                                    |
                                                 |                                    |
                                 [Library file]--*                                    V
                                                                       [Running Executable in Memory]

How to remove focus from single editText

Since I was in a widget and not in an activity I did:

`getRootView().clearFocus();

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

ASP.NET postback with JavaScript

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

Any easy way to use icons from resources?

On Form_Load:

this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;

How to print a dictionary's key?

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

git rebase fatal: Needed a single revision

You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase.

E.g.:

git rebase origin/master

not:

git rebase origin

Note, although origin should resolve to the the ref origin/HEAD when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

It sounds like you have file in the git repo owned by root. Since you're ssh'ing in as 'username' to do the push, the files must be writable by username. The easiest thing is probably to create the repo as the user, and use the same user to do your pushes. Another option is to create a group, make everything writable by the group, and make your user a member of that group.

Sublime Text 2 - Show file navigation in sidebar

  1. open ST ( Sublime Text )

  2. add your project root folder into ST : link : https://stackoverflow.com/a/18798528/1241980

  3. show sidebar : Menu bar View > Side Bar > Show Side Bar

  4. Try Ctrl + P to open a file someFileName.py

Does a navigation panel for openned files and project folders appear in the left of ST ?

Extra : Want view the other files that are in the same directory with someFileName.py ?
While I found ST side bar seems doesn't support this, but you can try Ctrl + O (Open) keyshort in ST to open your system file browser, in which the ST will help you to locate into the folder that contains someFileName.py and it's sibling files.

HTML: Changing colors of specific words in a string of text

<font color="red">This is some text!</font> 

This worked the best for me when I only wanted to change one word into the color red in a sentence.

How can I pass variable to ansible playbook in the command line?

ansible-playbook release.yml --extra-vars "username=hello password=bye"

#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check whether a file is empty or not?

Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

How to execute a raw update sql with dynamic binding in rails

In Rails 3.1, you should use the query interface:

  • new(attributes)
  • create(attributes)
  • create!(attributes)
  • find(id_or_array)
  • destroy(id_or_array)
  • destroy_all
  • delete(id_or_array)
  • delete_all
  • update(ids, updates)
  • update_all(updates)
  • exists?

update and update_all are the operation you need.

See details here: http://m.onkey.org/active-record-query-interface

Do I need <class> elements in persistence.xml?

Do I need Class elements in persistence.xml?

No, you don't necessarily. Here is how you do it in Eclipse (Kepler tested):

Right click on the project, click Properties, select JPA, in the Persistence class management tick Discover annotated classes automatically.

enter image description here

HTML Entity Decode

To add yet another "inspired by Robert K" to the list, here is another safe version which does not strip HTML tags. Instead of running the whole string through the HTML parser, it pulls out only the entities and converts those.

var decodeEntities = (function() {
    // this prevents any overhead from creating the object each time
    var element = document.createElement('div');

    // regular expression matching HTML entities
    var entity = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig;

    return function decodeHTMLEntities(str) {
        // find and replace all the html entities
        str = str.replace(entity, function(m) {
            element.innerHTML = m;
            return element.textContent;
        });

        // reset the value
        element.textContent = '';

        return str;
    }
})();

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

Creating a very simple linked list

public class Node<T>
{
    public T item;
    public Node<T> next;
    public Node()
    {
        this.next = null;
    }
}


class LinkList<T>
{
    public Node<T> head { get; set; }
    public LinkList()
    {
        this.head = null;
    }


    public void AddAtHead(T item)
    {
        Node<T> newNode = new Node<T>();
        newNode.item = item;
        if (this.head == null)
        {
            this.head = newNode;
        }
        else
        {
            newNode.next = head;
            this.head = newNode;
        }
    }

    public void AddAtTail(T item)
    {
        Node<T> newNode = new Node<T>();
        newNode.item = item;
        if (this.head == null)
        {
            this.head = newNode;
        }
        else
        {
            Node<T> temp = this.head;
            while (temp.next != null)
            {
                temp = temp.next;
            }
            temp.next = newNode;
        }
    }

    public void DeleteNode(T item)
    {
        if (this.head.item.Equals(item))
        {
            head = head.next;
        }
        else
        {
            Node<T> temp = head;
            Node<T> tempPre = head;
            bool matched = false;
            while (!(matched = temp.item.Equals(item)) && temp.next != null)
            {
                tempPre = temp;
                temp = temp.next;
            }
            if (matched)
            {
                tempPre.next = temp.next;
            }
            else
            {
                Console.WriteLine("Value not found!");
            }
        }
    }

    public bool searchNode(T item)
    {
        Node<T> temp = this.head;
        bool matched = false;
        while (!(matched = temp.item.Equals(item)) && temp.next != null)
        {
            temp = temp.next;
        }
        return matched;

    }
    public void DisplayList()
    {
        Console.WriteLine("Displaying List!");
        Node<T> temp = this.head;
        while (temp != null)
        {
            Console.WriteLine(temp.item);
            temp = temp.next;
        }
    }

}

Using AJAX to pass variable to PHP and retrieve those using AJAX again

No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.

SO, I recommend using one AJAX call and get the value with success.

example: in first ajax call

    $.ajax({
        url: 'ajax.php', //This is the current doc
        type: "POST",
        data: ({name: 145}),
        success: function(data){
            console.log(data);
            alert(data);
            //or if the data is JSON
            var jdata = jQuery.parseJSON(data);
        }
    }); 

How do I serialize an object and save it to a file in Android?

I just made a class to handle this with Generics, so it can be used with all the object types that are serializable:

public class SerializableManager {

    /**
     * Saves a serializable object.
     *
     * @param context The application context.
     * @param objectToSave The object to save.
     * @param fileName The name of the file.
     * @param <T> The type of the object.
     */

    public static <T extends Serializable> void saveSerializable(Context context, T objectToSave, String fileName) {
        try {
            FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(objectToSave);

            objectOutputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Loads a serializable object.
     *
     * @param context The application context.
     * @param fileName The filename.
     * @param <T> The object type.
     *
     * @return the serializable object.
     */

    public static<T extends Serializable> T readSerializable(Context context, String fileName) {
        T objectToReturn = null;

        try {
            FileInputStream fileInputStream = context.openFileInput(fileName);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            objectToReturn = (T) objectInputStream.readObject();

            objectInputStream.close();
            fileInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return objectToReturn;
    }

    /**
     * Removes a specified file.
     *
     * @param context The application context.
     * @param filename The name of the file.
     */

    public static void removeSerializable(Context context, String filename) {
        context.deleteFile(filename);
    }

}

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

Switch focus between editor and integrated terminal in Visual Studio Code

It's not exactly what is asked, but I found it very useful and related.

If someone wants to change from one terminal to another terminal also open in the integrate terminal panel of Visual Studio, you can search for:

Terminal: Focus Next Terminal

Or add the following key shortcut and do it faster with keyboard combination.

  {
    "key": "alt+cmd+right",
    "command": "workbench.action.terminal.focusNext",
    "when": "terminalFocus"
  },
  {
    "key": "alt+cmd+left",
    "command": "workbench.action.terminal.focusPrevious",
    "when": "terminalFocus"
  },

How to implement the Java comparable interface?

You just have to define that Animal implements Comparable<Animal> i.e. public class Animal implements Comparable<Animal>. And then you have to implement the compareTo(Animal other) method that way you like it.

@Override
public int compareTo(Animal other) {
    return Integer.compare(this.year_discovered, other.year_discovered);
}

Using this implementation of compareTo, animals with a higher year_discovered will get ordered higher. I hope you get the idea of Comparable and compareTo with this example.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

what worked for me is changing from http to ssh:

git remote rm origin
git remote add origin [email protected]:username/repoName.git

then check it with git remote -v

T-SQL Subquery Max(Date) and Joins

Something like this

SELECT * 
FROM MyParts 
LEFT JOIN 
(
SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
) myprice
 ON MyParts.Partid = MyPrice.Partid 

If you know your partid or can restrict it put it inside the join.

   SELECT myprice.partid, myprice.partdate, myprice2.Price, * 
    FROM MyParts 
    LEFT JOIN 
    (
    SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
    ) myprice
     ON MyParts.Partid = MyPrice.Partid 
    Inner Join MyPrice myprice2
    on myprice2.pricedate = myprice.pricedate
    and myprice2.partid = myprice.partid

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

How to compare two Dates without the time portion?

This is what worked for me:

var Date1 = new Date(dateObject1.toDateString()); //this sets time to 00:00:00
var Date2 = new Date(dateObject2.toDateString()); 
//do a normal compare
if(Date1 > Date2){ //do something }

Best method to download image from url in Android

Try this code to download an image from a URL on Android:

DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

My pycharm ce had the same error, was easy to fix it, if someone has that error, just uninstall and delete the folder, use ctrl+h if you can't find the folder in your documents, install the software again and should work again.

Remember to save the scratches folder before erasing the pycharm folder.

How to terminate the script in JavaScript?

If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror as shown in cross-exit:

function exit(code) {
    const prevOnError = window.onerror
    window.onerror = () => {
        window.onerror = prevOnError
        return true
    }

    throw new Error(`Script termination with code ${code || 0}.`)
}

console.log("This message is logged.");
exit();
console.log("This message isn't logged.");

Android - Launcher Icon Size

No need for third party tools when Android Studio can generate icons for us.

  • File -> New -> Image Asset

  • Then choose Launcher Icons as the Asset Type:

  • Choose a High-res image for the Image file:

Android Generate Launcher Icons

  • Next -> Finish to generate icons

generate ic laucher icons

Finally update android:icon name field in AndroidManifest.xml if required.

When do I have to use interfaces instead of abstract classes?

Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

Interface : It define just protocol which all subclass need to follow.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Don't include the whole play services library but use the one that you need.Replace the line in your build.gradle:

compile 'com.google.android.gms:play-services:9.6.1'

with the appropriate one from Google Play Services APIs,like for example:

compile 'com.google.android.gms:play-services-gcm:9.6.1'

How can I make XSLT work in chrome?

I had the same problem on localhost. Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files and enter your password (if you have one).

Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.

Foreach loop, determine which is the last iteration of the loop

Improving Daniel Wolf answer even further you could stack on another IEnumerable to avoid multiple iterations and lambdas such as:

var elements = new[] { "A", "B", "C" };
foreach (var e in elements.Detailed())
{
    if (!e.IsLast) {
        Console.WriteLine(e.Value);
    } else {
        Console.WriteLine("Last one: " + e.Value);
    }
}

The extension method implementation:

public static class EnumerableExtensions {
    public static IEnumerable<IterationElement<T>> Detailed<T>(this IEnumerable<T> source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        using (var enumerator = source.GetEnumerator())
        {
            bool isFirst = true;
            bool hasNext = enumerator.MoveNext();
            int index = 0;
            while (hasNext)
            {
                T current = enumerator.Current;
                hasNext = enumerator.MoveNext();
                yield return new IterationElement<T>(index, current, isFirst, !hasNext);
                isFirst = false;
                index++;
            }
        }
    }

    public struct IterationElement<T>
    {
        public int Index { get; }
        public bool IsFirst { get; }
        public bool IsLast { get; }
        public T Value { get; }

        public IterationElement(int index, T value, bool isFirst, bool isLast)
        {
            Index = index;
            IsFirst = isFirst;
            IsLast = isLast;
            Value = value;
        }
    }
}

How to change status bar color to match app in Lollipop? [Android]

In android pre Lollipop devices you can do it from SystemBarTintManager If you are using android studio just add Systembartint lib in your gradle file.

dependencies {
    compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'
    ...
}

Then in your activity

// create manager instance after the content view is set
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
// enable status bar tint
mTintManager.setStatusBarTintEnabled(true);
mTintManager.setTintColor(getResources().getColor(R.color.blue));

how can I enable scrollbars on the WPF Datagrid?

In my case I had to set MaxHeight and replace IsEnabled="False" by IsReadOnly="True"

How to remove only 0 (Zero) values from column in excel 2010

Some of the other answers are great for removing zeros from existing data, but if you have a working sheet that is constantly changed and want to prevent zeros from ever appearing, I find it's easiest to use conditional formatting to make them invisible. Just select the range of cells you want to apply it to > conditional formatting > new rule.

Change the rule type to "format only cells that contain" Cell value > equal to > 0.

Under "Format" change the text colour to white or whatever your background happens to be, and all cells which contain exactly zero will disappear.

Obviously this also works with any other value you want to make disappear.

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

How to remove blank lines from a Unix file

You can sed's -i option to edit in-place without using temporary file:

 sed -i '/^$/d' file

Where should I put the CSS and Javascript code in an HTML webpage?

Put Stylesheets at the Top Links to discussion

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively.

Front-end engineers that care about performance want a page to load progressively; that is, we want the browser to display whatever content it has as soon as possible. This is especially important for pages with a lot of content and for users on slower Internet connections. The importance of giving users visual feedback, such as progress indicators, has been well researched and documented. In our case the HTML page is the progress indicator! When the browser loads the page progressively the header, the navigation bar, the logo at the top, etc. all serve as visual feedback for the user who is waiting for the page. This improves the overall user experience.

The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.

The HTML specification clearly states that stylesheets are to be included in the HEAD of the page: "Unlike A, [LINK] may only appear in the HEAD section of a document, although it may appear any number of times." Neither of the alternatives, the blank white screen or flash of unstyled content, are worth the risk. The optimal solution is to follow the HTML specification and load your stylesheets in the document HEAD.

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

How to access a property of an object (stdClass Object) member/element of an array?

You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array

$object = array_shift($array);
var_dump($object->id);

Or refer to the thing by its index in the array.

var_dump( $array[0]->id );

Or, if you're not sure how many things are in the array, loop over the array

foreach($array as $key=>$value)
{
    var_dump($value->id);
    var_dump($array[$key]->id);
}

How to remove word wrap from textarea?

I found a way to make a textarea with all this working at the same time:

  • With horizontal scrollbar
  • Supporting multiline text
  • Text not wrapping

It works well on:

  • Chrome 15.0.874.120
  • Firefox 7.0.1
  • Opera 11.52 (1100)
  • Safari 5.1 (7534.50)
  • IE 8.0.6001.18702

Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

textarea {
  white-space:nowrap;
  overflow:scroll;
}

In the CSS section I used just this for IE:

textarea {
  overflow:scroll;
}

It was a bit tricky, but there is the CSS.

An (x)HTML tag like this:

<textarea id="myTextarea" rows="10" cols="15"></textarea>

And at the end of the <head> section a JavaScript like this:

 window.onload=function(){
   document.getElementById("myTextarea").wrap='off';
 }

The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

"unable to locate adb" using Android Studio

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

Spring-Security-Oauth2: Full authentication is required to access this resource

setting management.security.enabled=false in application.properties resolved the issue for me.

Select multiple columns from a table, but group by one

mysql GROUP_CONCAT function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
FROM OrderDetails GROUP BY ProductID

This would return:

ProductID     Names          OrderQuantity
1001          red            5
1002          red,black      6
1003          orange         8
1004          black,orange   15

Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265

How to finish Activity when starting other activity in Android?

You need to intent your current context to another activity first with startActivity. After that you can finish your current activity from where you redirect.

 Intent intent = new Intent(this, FirstActivity.class);// New activity
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 finish(); // Call once you redirect to another activity

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.

Val and Var in Kotlin

val (from value): Immutable reference. A variable declared with val can’t be reassigned after it’s initialized. It corresponds to a final variable in Java.

var (from variable): Mutable reference. The value of such a variable can be changed. This declaration corresponds to a regular (non-final) Java variable.

wait() or sleep() function in jquery?

Realize that this is an old question, but I wrote a plugin to address this issue that someone might find useful.

https://github.com/madbook/jquery.wait

lets you do this:

$('#myElement').addClass('load').wait(2000).addClass('done');

Calling a class method raises a TypeError in Python

You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.

length and length() in Java

.length is a one-off property of Java. It's used to find the size of a single dimensional array.

.length() is a method. It's used to find the length of a String. It avoids duplicating the value.

Why does HTML think “chucknorris” is a color?

The reason is the browser can not understand it and try to somehow translate it to what it can understand and in this case into a hexadecimal value!...

chucknorris starts with c which is recognised character in hexadecimal, also it's converting all unrecognised characters into 0!

So chucknorris in hexadecimal format becomes: c00c00000000, all other characters become 0 and c remains where they are...

Now they get divided by 3 for RGB(red, green, blue)... R: c00c, G: 0000, B:0000...

But we know valid hexadecimal for RGB is just 2 characters, means R: c0, G: 00, B:00

So the real result is:

bgcolor="#c00000";

I also added the steps in the image as a quick reference for you:

Why does HTML think “chucknorris” is a colour?

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

Short form for Java if statement

Use the ternary operator:

name = ((city.getName() == null) ? "N/A" : city.getName());

I think you have the conditions backwards - if it's null, you want the value to be "N/A".

What if city is null? Your code *hits the bed in that case. I'd add another check:

name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());

node.js hash string?

Simple One Liners:

If you want UTF8 text hash:

const hash = require('crypto').createHash('sha256').update('Hash me', 'utf8').digest('hex');

If you want to get the same hash with Python, PHP, Perl, Github:

const hash = require('crypto').createHash('sha256').update('Hash me', 'binary').digest('hex');

You can also replace 'sha256' with 'sha1', 'md5', 'sha256', 'sha512'

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

Push origin master error on new repository

I have this error too, i put a commit for not push empty project like a lot of people do but doesn't work

The problem was the ssl, y put the next

git config --system http.sslverify false

And after that everything works fine :)

git push origin master

Parsing a pcap file in python

You might want to start with scapy.

How do you create an asynchronous HTTP request in JAVA?

It has to be made clear the HTTP protocol is synchronous and this has nothing to do with the programming language. Client sends a request and gets a synchronous response.

If you want to an asynchronous behavior over HTTP, this has to be built over HTTP (I don't know anything about ActionScript but I suppose that this is what the ActionScript does too). There are many libraries that could give you such functionality (e.g. Jersey SSE). Note that they do somehow define dependencies between the client and the server as they do have to agree on the exact non standard communication method above HTTP.

If you cannot control both the client and the server or if you don't want to have dependencies between them, the most common approach of implementing asynchronous (e.g. event based) communication over HTTP is using the webhooks approach (you can check this for an example implementation in java).

Hope I helped!

Multiple arguments to function called by pthread_create()?

Use:

struct arg_struct *args = malloc(sizeof(struct arg_struct));

And pass this arguments like this:

pthread_create(&tr, NULL, print_the_arguments, (void *)args);

Don't forget free args! ;)

Changing password with Oracle SQL Developer

Your users can still change their passwords by "alter user onlyTheirUserName identified by newpassword". They do not have to have the ALTER USER privilege to change their own password.

How to safely call an async method in C# without await

This is called fire and forget, and there is an extension for that.

Consumes a task and doesn't do anything with it. Useful for fire-and-forget calls to async methods within async methods.

Install nuget package.

Use:

MyAsyncMethod().Forget();

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

Sql Server return the value of identity column after insert statement

Here goes a bunch of different ways to get the ID, including Scope_Identity:

https://stackoverflow.com/a/42655/1504882

Creating a range of dates in Python

Here's a slightly different answer building off of S.Lott's answer that gives a list of dates between two dates start and end. In the example below, from the start of 2017 to today.

start = datetime.datetime(2017,1,1)
end = datetime.datetime.today()
daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

Moment js get first and last day of current month

There would be another way to do this:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

Generating a PNG with matplotlib when DISPLAY is undefined

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:

import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
    matplotlib.use('Agg')

# now import other things from matplotlib
import matplotlib.pyplot as plt

Credit: https://stackoverflow.com/a/45756291/207661

Using regular expression in css?

You can' just add a class to each of your DIVs and apply the rule to the class in this way:

HTML:

<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>

CSS:

//css
.myclass
{
   ...
}

Get the last item in an array

The "cleanest" ES6 way (IMO) would be:

const foo = [1,2,3,4];
const bar = [...foo].pop();

This avoids mutating foo, as .pop() would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0] solution.

How can I show three columns per row?

Try this one using Grid Layout:

_x000D_
_x000D_
.grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: auto auto auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
  background-color: rgba(255, 255, 255, 0.8);_x000D_
  border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
  padding: 20px;_x000D_
  font-size: 30px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
  <div class="grid-item">1</div>_x000D_
  <div class="grid-item">2</div>_x000D_
  <div class="grid-item">3</div>  _x000D_
  <div class="grid-item">4</div>_x000D_
  <div class="grid-item">5</div>_x000D_
  <div class="grid-item">6</div>  _x000D_
  <div class="grid-item">7</div>_x000D_
  <div class="grid-item">8</div>_x000D_
  <div class="grid-item">9</div>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I find if a string starts with another string in Ruby?

Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:

irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
=> 12.477248
irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
=> 9.593959
irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
=> 9.086909
irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
=> 6.973697

So it looks like start_with? ist the fastest of the bunch.

Updated results with Ruby 2.2.2p95 and a newer machine:

require 'benchmark'
Benchmark.bm do |x|
  x.report('regex[]')    { 10000000.times { "foobar"[/\Afoo/] }}
  x.report('regex')      { 10000000.times { "foobar" =~ /\Afoo/ }}
  x.report('[]')         { 10000000.times { "foobar"["foo"] }}
  x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
end

            user       system     total       real
regex[]     4.020000   0.000000   4.020000 (  4.024469)
regex       3.160000   0.000000   3.160000 (  3.159543)
[]          2.930000   0.000000   2.930000 (  2.931889)
start_with  2.010000   0.000000   2.010000 (  2.008162)

How can I restart a Java application?

Although this question is old and answered, I've stumbled across a problem with some of the solutions and decided to add my suggestion into the mix.

The problem with some of the solutions is that they build a single command string. This creates issues when some parameters contain spaces, especially java.home.

For example, on windows, the line

final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";

Might return something like this:C:\Program Files\Java\jre7\bin\java

This string has to be wrapped in quotes or escaped due to the space in Program Files. Not a huge problem, but somewhat annoying and error prone, especially in cross platform applications.

Therefore my solution builds the command as an array of commands:

public static void restart(String[] args) {

        ArrayList<String> commands = new ArrayList<String>(4 + jvmArgs.size() + args.length);
        List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();

        // Java
        commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");

        // Jvm arguments
        for (String jvmArg : jvmArgs) {
            commands.add(jvmArg);
        }

        // Classpath
        commands.add("-cp");
        commands.add(ManagementFactory.getRuntimeMXBean().getClassPath());

        // Class to be executed
        commands.add(BGAgent.class.getName());

        // Command line arguments
        for (String arg : args) {
            commands.add(arg);
        }

        File workingDir = null; // Null working dir means that the child uses the same working directory

        String[] env = null; // Null env means that the child uses the same environment

        String[] commandArray = new String[commands.size()];
        commandArray = commands.toArray(commandArray);

        try {
            Runtime.getRuntime().exec(commandArray, env, workingDir);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

JSON find in JavaScript

Ok. So, I know this is an old post, but perhaps this can help someone else. This is not backwards compatible, but that's almost irrelevant since Internet Explorer is being made redundant.

Easiest way to do exactly what is wanted:

function findInJson(objJsonResp, key, value, aType){        
     if(aType=="edit"){
        return objJsonResp.find(x=> x[key] == value);
     }else{//delete
         var a =objJsonResp.find(x=> x[key] == value);
         objJsonResp.splice(objJsonResp.indexOf(a),1);
     }
}

It will return the item you want to edit if you supply 'edit' as the type. Supply anything else, or nothing, and it assumes delete. You can flip the conditionals if you'd prefer.

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

How to change CSS using jQuery?

_x000D_
_x000D_
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I concatenate two text files in PowerShell?

Simply use the Get-Content and Set-Content cmdlets:

Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt

You can concatenate more than two files with this style, too.

If the source files are named similarly, you can use wildcards:

Get-Content inputFile*.txt | Set-Content joinedFile.txt

Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat and sc for Get-Content and Set-Content respectively. However, these aliases are problematic because cat is a system command in *nix systems, and sc is a system command in Windows systems - therefore using them is not recommended, and in fact sc is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.

Note 2: Be careful with wildcards - if you try to output to examples.txt (or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)

Note 3: Outputting to a file with > does not preserve character encoding! This is why using Set-Content is recommended.

Should IBOutlets be strong or weak under ARC?

It looks like something has changed over the years and now Apple recommends to use strong in general. The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. My note from what he says is (almost, if not exactly, quoting him):

  • outlet connections in general should be strong especially if we connect a subview or constraint that is not always retained by the view hierarchy

  • weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended

In other wards it should be always strong now as long as some of our custom view doesn't create a retain cycle with some of the view up in the view hierarchy

EDIT :

Some may ask the question. Does keeping it with a strong reference doesn't create a retain cycle as the root view controller and the owning view keeps the reference to it? Or why that changed happened? I think the answer is earlier in this talk when they describe how the nibs are created from the xib. There is a separate nib created for a VC and for the view. I think this might be the reason why they change the recommendations. Still it would be nice to get a deeper explanation from Apple.

Typing the Enter/Return key using Python and Selenium

I had to send the Enter key in the middle of a text. So I passed the following text to send keys function to achieve 1\n2\n3:

1\N{U+E007}2\N{U+E007}3

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

OpenSSL Command to check if a server is presenting a certificate

I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.

Mod in Java produces negative numbers

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

Wait Until File Is Completely Written

Well you already give the answer yourself; you have to wait for the creation of the file to finish. One way to do this is via checking if the file is still in use. An example of this can be found here: Is there a way to check if a file is in use?

Note that you will have to modify this code for it to work in your situation. You might want to have something like (pseudocode):

public static void listener_Created()
{
   while CheckFileInUse()
      wait 1000 milliseconds

   CopyFile()
}

Obviously you should protect yourself from an infinite while just in case the owner application never releases the lock. Also, it might be worth checking out the other events from FileSystemWatcher you can subscribe to. There might be an event which you can use to circumvent this whole problem.

How can I split a text into sentences?

Instead of using regex for spliting the text into sentences, you can also use nltk library.

>>> from nltk import tokenize
>>> p = "Good morning Dr. Adams. The patient is waiting for you in room number 3."

>>> tokenize.sent_tokenize(p)
['Good morning Dr. Adams.', 'The patient is waiting for you in room number 3.']

ref: https://stackoverflow.com/a/9474645/2877052

Excel how to fill all selected blank cells with text

If you want to do this in VBA, then this is a shorter method:

Sub FillBlanksWithNull()

'This macro will fill all "blank" cells with the text "Null"

'When no range is selected, it starts at A1 until the last used row/column

'When a range is selected prior, only the blank cell in the range will be used.

On Error GoTo ErrHandler:

Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "Null"

Exit Sub

ErrHandler:

MsgBox "No blank cells found", vbDefaultButton1, Error

Resume Next

End Sub

Regards,

Robert Ilbrink

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Windows- Pyinstaller Error "failed to execute script " When App Clicked

I got the same error and figured out that i wrote my script using Anaconda but pyinstaller tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.

Combine multiple results in a subquery into a single comma-separated value

SELECT t.ID, 
       t.NAME, 
       (SELECT t1.SOMECOLUMN 
        FROM   TABLEB t1 
        WHERE  t1.F_ID = T.TABLEA.ID) 
FROM   TABLEA t; 

This will work for selecting from different table using sub query.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

Is there a Subversion command to reset the working copy?

Delete the working copy from the OS and check it out again is simplest, but obviously not a single command.

Hiding a button in Javascript

document.getElementById('btnID').style.visibility='hidden';

Rounding numbers to 2 digits after comma

EDIT 2:

Use the Number object's toFixed method like this:

var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)

It rounds 42.0054321 to 42.01

It rounds 0.005 to 0.01

It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

jsFiddle example

How does the vim "write with sudo" trick work?

In :w !sudo tee %...

% means "the current file"

As eugene y pointed out, % does indeed mean "the current file name", which is passed to tee so that it knows which file to overwrite.

(In substitution commands, it's slightly different; as :help :% shows, it's equal to 1,$ (the entire file) (thanks to @Orafu for pointing out that this does not evaluate to the filename). For example, :%s/foo/bar means "in the current file, replace occurrences of foo with bar." If you highlight some text before typing :s, you'll see that the highlighted lines take the place of % as your substitution range.)

:w isn't updating your file

One confusing part of this trick is that you might think :w is modifying your file, but it isn't. If you opened and modified file1.txt, then ran :w file2.txt, it would be a "save as"; file1.txt wouldn't be modified, but the current buffer contents would be sent to file2.txt.

Instead of file2.txt, you can substitute a shell command to receive the buffer contents. For instance, :w !cat will just display the contents.

If Vim wasn't run with sudo access, its :w can't modify a protected file, but if it passes the buffer contents to the shell, a command in the shell can be run with sudo. In this case, we use tee.

Understanding tee

As for tee, picture the tee command as a T-shaped pipe in a normal bash piping situation: it directs output to specified file(s) and also sends it to standard output, which can be captured by the next piped command.

For example, in ps -ax | tee processes.txt | grep 'foo', the list of processes will be written to a text file and passed along to grep.

     +-----------+    tee     +------------+
     |           |  --------  |            |
     | ps -ax    |  --------  | grep 'foo' |
     |           |     ||     |            |
     +-----------+     ||     +------------+
                       ||   
               +---------------+
               |               |
               | processes.txt |
               |               |
               +---------------+

(Diagram created with Asciiflow.)

See the tee man page for more info.

Tee as a hack

In the situation your question describes, using tee is a hack because we're ignoring half of what it does. sudo tee writes to our file and also sends the buffer contents to standard output, but we ignore standard output. We don't need to pass anything to another piped command in this case; we're just using tee as an alternate way of writing a file and so that we can call it with sudo.

Making this trick easy

You can add this to your .vimrc to make this trick easy-to-use: just type :w!!.

" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %

The > /dev/null part explicitly throws away the standard output, since, as I said, we don't need to pass anything to another piped command.

Dark color scheme for Eclipse

Easiest way: change the Windows Display Properties main window background color. I went to Appearance tab, changed to Silver scheme, clicked Advanced, clicked on "Active Window" and changed Color 1 to a light gray. All Eclipse views softened.

Since Luna (4.4) there seems to be a full Dark them in

Window -> Preferences -> General -> Appearance -> Theme -> Dark

enter image description here

Android notification is not showing

For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.

For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.

// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
  new OnSuccessListener<InstanceIdResult>() {

    @Override
    public void onSuccess(InstanceIdResult instanceIdResult) {

        deviceToken = instanceIdResult.getToken();

        // Insert device token into Firebase database
        fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
                .addOnSuccessListener(
                  new OnSuccessListener<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {

                    }
                });
    }
});

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)
                              ^

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

How to add two strings as if they were numbers?

I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:

(+varname)

So, in your case it's:

var num1 = '20',
    num2 = '30.5';

var sum = (+num1) + (+num2);

// Just to test it
console.log( sum ); // 50.5

Use formula in custom calculated field in Pivot Table

Pivot table Excel2007- average to exclude zeros

=sum(XX:XX)/count if(XX:XX, ">0")

Invoice USD

Qty Rate(count) Value (sum) 300 0.000 000.000 1000 0.385 385.000

Average Rate Count should Exclude 0.000 rate

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

Reorder HTML table rows using drag-and-drop

Building upon the fiddle from @tim, this version tightens the scope and formatting, and converts bind() -> on(). It's designed to bind on a dedicated td as the handle instead of the entire row. In my use case, I have input fields so the "drag anywhere on the row" approach felt confusing.

Tested working on desktop. Only partial success with mobile touch. Can't get it to run correctly on SO's runnable snippet for some reason...

_x000D_
_x000D_
let ns = {
  drag: (e) => {
    let el = $(e.target),
      d = $('body'),
      tr = el.closest('tr'),
      sy = e.pageY,
      drag = false,
      index = tr.index();

    tr.addClass('grabbed');

    function move(e) {
      if (!drag && Math.abs(e.pageY - sy) < 10)
        return;
      drag = true;
      tr.siblings().each(function() {
        let s = $(this),
          i = s.index(),
          y = s.offset().top;
        if (e.pageY >= y && e.pageY < y + s.outerHeight()) {
          i < tr.index() ? s.insertAfter(tr) : s.insertBefore(tr);
          return false;
        }
      });
    }

    function up(e) {
      if (drag && index !== tr.index())
        drag = false;

      d.off('mousemove', move).off('mouseup', up);
      //d.off('touchmove', move).off('touchend', up); //failed attempt at touch compatibility
      tr.removeClass('grabbed');
    }
    d.on('mousemove', move).on('mouseup', up);
    //d.on('touchmove', move).on('touchend', up);
  }
};

$(document).ready(() => {
  $('body').on('mousedown touchstart', '.drag', ns.drag);
});
_x000D_
.grab {
  cursor: grab;
  user-select: none
}

tr.grabbed {
  box-shadow: 4px 1px 5px 2px rgba(0, 0, 0, 0.5);
}

tr.grabbed:active {
  user-input: none;
}

tr.grabbed:active * {
  user-input: none;
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Drag the rows below...</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 1" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 2" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 3" /></td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

calculating the difference in months between two dates

The accepted answer is strongly incorrect:

For these dates: ldate = 2020-08-30 and rdate = 2020-08-01, we have one month, but the accepted answer returns 0.

For these dates: ldate = 2020-08-30 and rdate = 2020-10-01, we have three months, but the accepted answer returns -2.

Here is the correct method (maybe not the unique method, but correct) to calculate the quantity of months between two dates:

  • You don't have to check which date is lower than other.

  • An interval from the first day to the last day of month is counted as a month.

      public static int GetMontsBetween(DateTime date1, DateTime date2)
      {
          int monthCount = 0;
          int direction = date1 < date2 ? 1 : -1;
          date2 = date2.AddDays(direction);
    
          while (date1.Year != date2.Year || date1.Month != date2.Month)
          {
              date1 = date1.AddMonths(direction);
              monthCount++;
          }
    
          return monthCount;
      } 
    

What's the most efficient way to erase duplicates and sort a vector?

The standard approach suggested by Nate Kohl, just using vector, sort + unique:

sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );

doesn't work for a vector of pointers.

Look carefully at this example on cplusplus.com.

In their example, the "so called duplicates" moved to the end are actually shown as ? (undefined values), because those "so called duplicates" are SOMETIMES "extra elements" and SOMETIMES there are "missing elements" that were in the original vector.

A problem occurs when using std::unique() on a vector of pointers to objects (memory leaks, bad read of data from HEAP, duplicate frees, which cause segmentation faults, etc).

Here's my solution to the problem: replace std::unique() with ptgi::unique().

See the file ptgi_unique.hpp below:

// ptgi::unique()
//
// Fix a problem in std::unique(), such that none of the original elts in the collection are lost or duplicate.
// ptgi::unique() has the same interface as std::unique()
//
// There is the 2 argument version which calls the default operator== to compare elements.
//
// There is the 3 argument version, which you can pass a user defined functor for specialized comparison.
//
// ptgi::unique() is an improved version of std::unique() which doesn't looose any of the original data
// in the collection, nor does it create duplicates.
//
// After ptgi::unique(), every old element in the original collection is still present in the re-ordered collection,
// except that duplicates have been moved to a contiguous range [dupPosition, last) at the end.
//
// Thus on output:
//  [begin, dupPosition) range are unique elements.
//  [dupPosition, last) range are duplicates which can be removed.
// where:
//  [] means inclusive, and
//  () means exclusive.
//
// In the original std::unique() non-duplicates at end are moved downward toward beginning.
// In the improved ptgi:unique(), non-duplicates at end are swapped with duplicates near beginning.
//
// In addition if you have a collection of ptrs to objects, the regular std::unique() will loose memory,
// and can possibly delete the same pointer multiple times (leading to SEGMENTATION VIOLATION on Linux machines)
// but ptgi::unique() won't.  Use valgrind(1) to find such memory leak problems!!!
//
// NOTE: IF you have a vector of pointers, that is, std::vector<Object*>, then upon return from ptgi::unique()
// you would normally do the following to get rid of the duplicate objects in the HEAP:
//
//  // delete objects from HEAP
//  std::vector<Object*> objects;
//  for (iter = dupPosition; iter != objects.end(); ++iter)
//  {
//      delete (*iter);
//  }
//
//  // shrink the vector. But Object * pointers are NOT followed for duplicate deletes, this shrinks the vector.size())
//  objects.erase(dupPosition, objects.end));
//
// NOTE: But if you have a vector of objects, that is: std::vector<Object>, then upon return from ptgi::unique(), it
// suffices to just call vector:erase(, as erase will automatically call delete on each object in the
// [dupPosition, end) range for you:
//
//  std::vector<Object> objects;
//  objects.erase(dupPosition, last);
//
//==========================================================================================================
// Example of differences between std::unique() vs ptgi::unique().
//
//  Given:
//      int data[] = {10, 11, 21};
//
//  Given this functor: ArrayOfIntegersEqualByTen:
//      A functor which compares two integers a[i] and a[j] in an int a[] array, after division by 10:
//  
//  // given an int data[] array, remove consecutive duplicates from it.
//  // functor used for std::unique (BUGGY) or ptgi::unique(IMPROVED)
//
//  // Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
//  // Hence 50..59 are equal, 60..69 are equal, etc.
//  struct ArrayOfIntegersEqualByTen: public std::equal_to<int>
//  {
//      bool operator() (const int& arg1, const int& arg2) const
//      {
//          return ((arg1/10) == (arg2/10));
//      }
//  };
//  
//  Now, if we call (problematic) std::unique( data, data+3, ArrayOfIntegersEqualByTen() );
//  
//  TEST1: BEFORE UNIQ: 10,11,21
//  TEST1: AFTER UNIQ: 10,21,21
//  DUP_INX=2
//  
//      PROBLEM: 11 is lost, and extra 21 has been added.
//  
//  More complicated example:
//  
//  TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,23,24,11
//  DUP_INX=5
//  
//      Problem: 21 and 22 are deleted.
//      Problem: 11 and 23 are duplicated.
//  
//  
//  NOW if ptgi::unique is called instead of std::unique, both problems go away:
//  
//  DEBUG: TEST1: NEW_WAY=1
//  TEST1: BEFORE UNIQ: 10,11,21
//  TEST1: AFTER UNIQ: 10,21,11
//  DUP_INX=2
//  
//  DEBUG: TEST2: NEW_WAY=1
//  TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//  DUP_INX=5
//
//  @SEE: look at the "case study" below to understand which the last "AFTER UNIQ" results with that order:
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//
//==========================================================================================================
// Case Study: how ptgi::unique() works:
//  Remember we "remove adjacent duplicates".
//  In this example, the input is NOT fully sorted when ptgi:unique() is called.
//
//  I put | separatators, BEFORE UNIQ to illustrate this
//  10  | 20,21,22 |  30,31 |  23,24 | 11
//
//  In example above, 20, 21, 22 are "same" since dividing by 10 gives 2 quotient.
//  And 30,31 are "same", since /10 quotient is 3.
//  And 23, 24 are same, since /10 quotient is 2.
//  And 11 is "group of one" by itself.
//  So there are 5 groups, but the 4th group (23, 24) happens to be equal to group 2 (20, 21, 22)
//  So there are 5 groups, and the 5th group (11) is equal to group 1 (10)
//
//  R = result
//  F = first
//
//  10, 20, 21, 22, 30, 31, 23, 24, 11
//  R    F
//
//  10 is result, and first points to 20, and R != F (10 != 20) so bump R:
//       R
//       F
//
//  Now we hits the "optimized out swap logic".
//  (avoid swap because R == F)
//
//  // now bump F until R != F (integer division by 10)
//  10, 20, 21, 22, 30, 31, 23, 24, 11
//       R   F              // 20 == 21 in 10x
//       R       F              // 20 == 22 in 10x
//       R           F          // 20 != 30, so we do a swap of ++R and F
//  (Now first hits 21, 22, then finally 30, which is different than R, so we swap bump R to 21 and swap with  30)
//  10, 20, 30, 22, 21, 31, 23, 24, 11  // after R & F swap (21 and 30)
//           R       F 
//
//  10, 20, 30, 22, 21, 31, 23, 24, 11
//           R          F           // bump F to 31, but R and F are same (30 vs 31)
//           R               F      // bump F to 23, R != F, so swap ++R with F
//  10, 20, 30, 22, 21, 31, 23, 24, 11
//                  R           F       // bump R to 22
//  10, 20, 30, 23, 21, 31, 22, 24, 11  // after the R & F swap (22 & 23 swap)
//                  R            F      // will swap 22 and 23
//                  R                F      // bump F to 24, but R and F are same in 10x
//                  R                    F  // bump F, R != F, so swap ++R  with F
//                      R                F  // R and F are diff, so swap ++R  with F (21 and 11)
//  10, 20, 30, 23, 11, 31, 22, 24, 21
//                      R                F  // aftter swap of old 21 and 11
//                      R                  F    // F now at last(), so loop terminates
//                          R               F   // bump R by 1 to point to dupPostion (first duplicate in range)
//
//  return R which now points to 31
//==========================================================================================================
// NOTES:
// 1) the #ifdef IMPROVED_STD_UNIQUE_ALGORITHM documents how we have modified the original std::unique().
// 2) I've heavily unit tested this code, including using valgrind(1), and it is *believed* to be 100% defect-free.
//
//==========================================================================================================
// History:
//  130201  dpb [email protected] created
//==========================================================================================================

#ifndef PTGI_UNIQUE_HPP
#define PTGI_UNIQUE_HPP

// Created to solve memory leak problems when calling std::unique() on a vector<Route*>.
// Memory leaks discovered with valgrind and unitTesting.


#include <algorithm>        // std::swap

// instead of std::myUnique, call this instead, where arg3 is a function ptr
//
// like std::unique, it puts the dups at the end, but it uses swapping to preserve original
// vector contents, to avoid memory leaks and duplicate pointers in vector<Object*>.

#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
#error the #ifdef for IMPROVED_STD_UNIQUE_ALGORITHM was defined previously.. Something is wrong.
#endif

#undef IMPROVED_STD_UNIQUE_ALGORITHM
#define IMPROVED_STD_UNIQUE_ALGORITHM

// similar to std::unique, except that this version swaps elements, to avoid
// memory leaks, when vector contains pointers.
//
// Normally the input is sorted.
// Normal std::unique:
// 10 20 20 20 30   30 20 20 10
// a  b  c  d  e    f  g  h  i
//
// 10 20 30 20 10 | 30 20 20 10
// a  b  e  g  i    f  g  h  i
//
// Now GONE: c, d.
// Now DUPS: g, i.
// This causes memory leaks and segmenation faults due to duplicate deletes of same pointer!


namespace ptgi {

// Return the position of the first in range of duplicates moved to end of vector.
//
// uses operator==  of class for comparison
//
// @param [first, last) is a range to find duplicates within.
//
// @return the dupPosition position, such that [dupPosition, end) are contiguous
// duplicate elements.
// IF all items are unique, then it would return last.
//
template <class ForwardIterator>
ForwardIterator unique( ForwardIterator first, ForwardIterator last)
{
    // compare iterators, not values
    if (first == last)
        return last;

    // remember the current item that we are looking at for uniqueness
    ForwardIterator result = first;

    // result is slow ptr where to store next unique item
    // first is  fast ptr which is looking at all elts

    // the first iterator moves over all elements [begin+1, end).
    // while the current item (result) is the same as all elts
    // to the right, (first) keeps going, until you find a different
    // element pointed to by *first.  At that time, we swap them.

    while (++first != last)
    {
        if (!(*result == *first))
        {
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
            // inc result, then swap *result and *first

//          THIS IS WHAT WE WANT TO DO.
//          BUT THIS COULD SWAP AN ELEMENT WITH ITSELF, UNCECESSARILY!!!
//          std::swap( *first, *(++result));

            // BUT avoid swapping with itself when both iterators are the same
            ++result;
            if (result != first)
                std::swap( *first, *result);
#else
            // original code found in std::unique()
            // copies unique down
            *(++result) = *first;
#endif
        }
    }

    return ++result;
}

template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique( ForwardIterator first, ForwardIterator last, BinaryPredicate pred)
{
    if (first == last)
        return last;

    // remember the current item that we are looking at for uniqueness
    ForwardIterator result = first;

    while (++first != last)
    {
        if (!pred(*result,*first))
        {
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
            // inc result, then swap *result and *first

//          THIS COULD SWAP WITH ITSELF UNCECESSARILY
//          std::swap( *first, *(++result));
//
            // BUT avoid swapping with itself when both iterators are the same
            ++result;
            if (result != first)
                std::swap( *first, *result);

#else
            // original code found in std::unique()
            // copies unique down
            // causes memory leaks, and duplicate ptrs
            // and uncessarily moves in place!
            *(++result) = *first;
#endif
        }
    }

    return ++result;
}

// from now on, the #define is no longer needed, so get rid of it
#undef IMPROVED_STD_UNIQUE_ALGORITHM

} // end ptgi:: namespace

#endif

And here is the UNIT Test program that I used to test it:

// QUESTION: in test2, I had trouble getting one line to compile,which was caused  by the declaration of operator()
// in the equal_to Predicate.  I'm not sure how to correctly resolve that issue.
// Look for //OUT lines
//
// Make sure that NOTES in ptgi_unique.hpp are correct, in how we should "cleanup" duplicates
// from both a vector<Integer> (test1()) and vector<Integer*> (test2).
// Run this with valgrind(1).
//
// In test2(), IF we use the call to std::unique(), we get this problem:
//
//  [dbednar@ipeng8 TestSortRoutes]$ ./Main7
//  TEST2: ORIG nums before UNIQUE: 10, 20, 21, 22, 30, 31, 23, 24, 11
//  TEST2: modified nums AFTER UNIQUE: 10, 20, 30, 23, 11, 31, 23, 24, 11
//  INFO: dupInx=5
//  TEST2: uniq = 10
//  TEST2: uniq = 20
//  TEST2: uniq = 30
//  TEST2: uniq = 33427744
//  TEST2: uniq = 33427808
//  Segmentation fault (core dumped)
//
// And if we run valgrind we seen various error about "read errors", "mismatched free", "definitely lost", etc.
//
//  valgrind --leak-check=full ./Main7
//  ==359== Memcheck, a memory error detector
//  ==359== Command: ./Main7
//  ==359== Invalid read of size 4
//  ==359== Invalid free() / delete / delete[]
//  ==359== HEAP SUMMARY:
//  ==359==     in use at exit: 8 bytes in 2 blocks
//  ==359== LEAK SUMMARY:
//  ==359==    definitely lost: 8 bytes in 2 blocks
// But once we replace the call in test2() to use ptgi::unique(), all valgrind() error messages disappear.
//
// 130212   dpb [email protected] created
// =========================================================================================================

#include <iostream> // std::cout, std::cerr
#include <string>
#include <vector>   // std::vector
#include <sstream>  // std::ostringstream
#include <algorithm>    // std::unique()
#include <functional>   // std::equal_to(), std::binary_function()
#include <cassert>  // assert() MACRO

#include "ptgi_unique.hpp"  // ptgi::unique()



// Integer is small "wrapper class" around a primitive int.
// There is no SETTER, so Integer's are IMMUTABLE, just like in JAVA.

class Integer
{
private:
    int num;
public:

    // default CTOR: "Integer zero;"
    // COMPRENSIVE CTOR:  "Integer five(5);"
    Integer( int num = 0 ) :
        num(num)
    {
    }

    // COPY CTOR
    Integer( const Integer& rhs) :
        num(rhs.num)
    {
    }

    // assignment, operator=, needs nothing special... since all data members are primitives

    // GETTER for 'num' data member
    // GETTER' are *always* const
    int getNum() const
    {
        return num;
    }   

    // NO SETTER, because IMMUTABLE (similar to Java's Integer class)

    // @return "num"
    // NB: toString() should *always* be a const method
    //
    // NOTE: it is probably more efficient to call getNum() intead
    // of toString() when printing a number:
    //
    // BETTER to do this:
    //  Integer five(5);
    //  std::cout << five.getNum() << "\n"
    // than this:
    //  std::cout << five.toString() << "\n"

    std::string toString() const
    {
        std::ostringstream oss;
        oss << num;
        return oss.str();
    }
};

// convenience typedef's for iterating over std::vector<Integer>
typedef std::vector<Integer>::iterator      IntegerVectorIterator;
typedef std::vector<Integer>::const_iterator    ConstIntegerVectorIterator;

// convenience typedef's for iterating over std::vector<Integer*>
typedef std::vector<Integer*>::iterator     IntegerStarVectorIterator;
typedef std::vector<Integer*>::const_iterator   ConstIntegerStarVectorIterator;

// functor used for std::unique or ptgi::unique() on a std::vector<Integer>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTen: public std::equal_to<Integer>
{
    bool operator() (const Integer& arg1, const Integer& arg2) const
    {
        return ((arg1.getNum()/10) == (arg2.getNum()/10));
    }
};

// functor used for std::unique or ptgi::unique on a std::vector<Integer*>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTenPointer: public std::equal_to<Integer*>
{
    // NB: the Integer*& looks funny to me!
    // TECHNICAL PROBLEM ELSEWHERE so had to remove the & from *&
//OUT   bool operator() (const Integer*& arg1, const Integer*& arg2) const
//
    bool operator() (const Integer* arg1, const Integer* arg2) const
    {
        return ((arg1->getNum()/10) == (arg2->getNum()/10));
    }
};

void test1();
void test2();
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums );

int main()
{
    test1();
    test2();
    return 0;
}

// test1() uses a vector<Object> (namely vector<Integer>), so there is no problem with memory loss
void test1()
{
    int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};

    // turn C array into C++ vector
    std::vector<Integer> nums(data, data+9);

    // arg3 is a functor
    IntegerVectorIterator dupPosition = ptgi::unique( nums.begin(), nums.end(), IntegerEqualByTen() );

    nums.erase(dupPosition, nums.end());

    nums.erase(nums.begin(), dupPosition);
}

//==================================================================================
// test2() uses a vector<Integer*>, so after ptgi:unique(), we have to be careful in
// how we eliminate the duplicate Integer objects stored in the heap.
//==================================================================================
void test2()
{
    int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};

    // turn C array into C++ vector of Integer* pointers
    std::vector<Integer*> nums;

    // put data[] integers into equivalent Integer* objects in HEAP
    for (int inx = 0; inx < 9; ++inx)
    {
        nums.push_back( new Integer(data[inx]) );
    }

    // print the vector<Integer*> to stdout
    printIntegerStarVector( "TEST2: ORIG nums before UNIQUE", nums );

    // arg3 is a functor
#if 1
    // corrected version which fixes SEGMENTATION FAULT and all memory leaks reported by valgrind(1)
    // I THINK we want to use new C++11 cbegin() and cend(),since the equal_to predicate is passed "Integer *&"

//  DID NOT COMPILE
//OUT   IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<ConstIntegerStarVectorIterator>(nums.begin()), const_cast<ConstIntegerStarVectorIterator>(nums.end()), IntegerEqualByTenPointer() );

    // DID NOT COMPILE when equal_to predicate declared "Integer*& arg1, Integer*&  arg2"
//OUT   IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<nums::const_iterator>(nums.begin()), const_cast<nums::const_iterator>(nums.end()), IntegerEqualByTenPointer() );


    // okay when equal_to predicate declared "Integer* arg1, Integer*  arg2"
    IntegerStarVectorIterator dupPosition = ptgi::unique(nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#else
    // BUGGY version that causes SEGMENTATION FAULT and valgrind(1) errors
    IntegerStarVectorIterator dupPosition = std::unique( nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#endif

    printIntegerStarVector( "TEST2: modified nums AFTER UNIQUE", nums );
    int dupInx = dupPosition - nums.begin();
    std::cout << "INFO: dupInx=" << dupInx <<"\n";

    // delete the dup Integer* objects in the [dupPosition, end] range
    for (IntegerStarVectorIterator iter = dupPosition; iter != nums.end(); ++iter)
    {
        delete (*iter);
    }

    // shrink the vector
    // NB: the Integer* ptrs are NOT followed by vector::erase()
    nums.erase(dupPosition, nums.end());


    // print the uniques, by following the iter to the Integer* pointer
    for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end();  ++iter)
    {
        std::cout << "TEST2: uniq = " << (*iter)->getNum() << "\n";
    }

    // remove the unique objects from heap
    for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end();  ++iter)
    {
        delete (*iter);
    }

    // shrink the vector
    nums.erase(nums.begin(), nums.end());

    // the vector should now be completely empty
    assert( nums.size() == 0);
}

//@ print to stdout the string: "info_msg: num1, num2, .... numN\n"
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums )
{
    std::cout << msg << ": ";
    int inx = 0;
    ConstIntegerStarVectorIterator  iter;

    // use const iterator and const range!
    // NB: cbegin() and cend() not supported until LATER (c++11)
    for (iter = nums.begin(), inx = 0; iter != nums.end(); ++iter, ++inx)
    {
        // output a comma seperator *AFTER* first
        if (inx > 0)
            std::cout << ", ";

        // call Integer::toString()
        std::cout << (*iter)->getNum();     // send int to stdout
//      std::cout << (*iter)->toString();   // also works, but is probably slower

    }

    // in conclusion, add newline
    std::cout << "\n";
}

Order columns through Bootstrap4

even this will work:

<div class="container">
            <div class="row">
                <div class="col-4 col-sm-4 col-md-6 order-1">
                    1
                </div>
                <div class="col-4 col-sm-4  col-md-6 order-3">
                    2
                </div>
                <div class="col-4 col-sm-4  col-md-12 order-2">
                    3
                </div>
            </div>
          </div>

Launch an app from within another (iPhone)

To achieve this we need to add few line of Code in both App

App A: Which you want to open from another App. (Source)

App B: From App B you want to open App A (Destination)

Code for App A

Add few tags into the Plist of App A Open Plist Source of App A and Past below XML

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>com.TestApp</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>testApp.linking</string>
        </array>
    </dict>
</array>

In App delegate of App A - Get Callback here

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// You we get the call back here when App B will try to Open 
// sourceApplication will have the bundle ID of the App B
// [url query] will provide you the whole URL 
// [url query] with the help of this you can also pass the value from App B and get that value here 
}

Now coming to App B code -

If you just want to open App A without any input parameter

-(IBAction)openApp_A:(id)sender{

    if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"testApp.linking://?"]]){
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"App is not available!" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];

        }
}

If you want to pass parameter from App B to App A then use below Code

-(IBAction)openApp_A:(id)sender{
    if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"testApp.linking://?userName=abe&registered=1&Password=123abc"]]){
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"App is not available!" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];

        }
}

Note: You can also open App with just type testApp.linking://? on safari browser

How to convert a String to JsonObject using gson library

String emailData = {"to": "[email protected]","subject":"User details","body": "The user has completed his training"
}

// Java model class
public class EmailData {
    public String to;
    public String subject;
    public String body;
}

//Final Data
Gson gson = new Gson();  
EmailData emaildata = gson.fromJson(emailData, EmailData.class);

Using R to download zipped data file, extract, and import data

For Mac (and I assume Linux)...

If the zip archive contains a single file, you can use the bash command funzip, in conjuction with fread from the data.table package:

library(data.table)
dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | funzip")

In cases where the archive contains multiple files, you can use tar instead to extract a specific file to stdout:

dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | tar -xf- --to-stdout *a1.dat")

JFrame: How to disable window resizing?

This Code May be Help you : [ Both maximizing and preventing resizing on a JFrame ]

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);

Git merge is not possible because I have unmerged files

Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.

In other words, merging "main" into "current" in the following arrangement:

main
  |
  --feature
      |
      --current

I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.

Determine distance from the top of a div to top of window with javascript

This can be achieved purely with JavaScript.

I see the answer I wanted to write has been answered by lynx in comments to the question.

But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.

So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:

// Fetch the element
var el = document.getElementById("someElement");  

use getBoundingClientRect()

// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top; 

Thats it!

Hope this helps someone :)

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].

This is becausemean_data[2] is a list. Further indexing is done recursively - since mean_data[2] is a list, mean_data[2][0] is the first index of that list.

Additionally, mean_data[:][0] does not work because mean_data[:] returns mean_data.

The solution is to replace the array ,or import the original data, as follows:

mean_data = np.array(mean_data)

numpy arrays (like MATLAB arrays and unlike nested lists) support multi-dimensional slicing with tuples.

How does RewriteBase work in .htaccess

RewriteBase is only applied to the target of a relative rewrite rule.

  • Using RewriteBase like this...

    RewriteBase /folder/
    RewriteRule a\.html b.html
    
  • is essentially the same as...

    RewriteRule a\.html /folder/b.html
    
  • But when the .htaccess file is inside /folder/ then this also points to the same target:

    RewriteRule a\.html b.html
    

Although the docs imply always using a RewriteBase, Apache usually detects it correctly for paths under the DocumentRoot unless:

  • You are using Alias directives

  • You are using .htaccess rewrite rules to perform HTTP redirects (rather than just silent rewriting) to relative URLs

In these cases, you may find that you need to specify the RewriteBase.

However, since it's a confusing directive, it's generally better to simply specify absolute (aka 'root relative') URIs in your rewrite targets. Other developers reading your rules will grasp these more easily.



Quoting from Jon Lin's excellent in-depth answer here:

In an htaccess file, mod_rewrite works similar to a <Directory> or <Location> container. and the RewriteBase is used to provide a relative path base.

For example, say you have this folder structure:

DocumentRoot
|-- subdir1
`-- subdir2
    `-- subsubdir

So you can access:

  • http://example.com/ (root)
  • http://example.com/subdir1 (subdir1)
  • http://example.com/subdir2 (subdir2)
  • http://example.com/subdir2/subsubdir (subsubdir)

The URI that gets sent through a RewriteRule is relative to the directory containing the htaccess file. So if you have:

RewriteRule ^(.*)$ - 
  • In the root htaccess, and the request is /a/b/c/d, then the captured URI ($1) is a/b/c/d.
  • If the rule is in subdir2 and the request is /subdir2/e/f/g then the captured URI is e/f/g.
  • If the rule is in the subsubdir, and the request is /subdir2/subsubdir/x/y/z, then the captured URI is x/y/z.

The directory that the rule is in has that part stripped off of the URI. The rewrite base has no affect on this, this is simply how per-directory works.

What the rewrite base does do, is provide a URL-path base (not a file-path base) for any relative paths in the rule's target. So say you have this rule:

RewriteRule ^foo$ bar.php [L]

The bar.php is a relative path, as opposed to:

RewriteRule ^foo$ /bar.php [L]

where the /bar.php is an absolute path. The absolute path will always be the "root" (in the directory structure above). That means that regardless of whether the rule is in the "root", "subdir1", "subsubdir", etc. the /bar.php path always maps to http://example.com/bar.php.

But the other rule, with the relative path, it's based on the directory that the rule is in. So if

RewriteRule ^foo$ bar.php [L]

is in the "root" and you go to http://example.com/foo, you get served http://example.com/bar.php. But if that rule is in the "subdir1" directory, and you go to http://example.com/subdir1/foo, you get served http://example.com/subdir1/bar.php. etc. This sometimes works and sometimes doesn't, as the documentation says, it's supposed to be required for relative paths, but most of the time it seems to work. Except when you are redirecting (using the R flag, or implicitly because you have http://host in your rule's target). That means this rule:

RewriteRule ^foo$ bar.php [L,R]

if it's in the "subdir2" directory, and you go to http://example.com/subdir2/foo, mod_rewrite will mistake the relative path as a file-path instead of a URL-path and because of the R flag, you'll end up getting redirected to something like: http://example.com/var/www/localhost/htdocs/subdir1. Which is obviously not what you want.

This is where RewriteBase comes in. The directive tells mod_rewrite what to append to the beginning of every relative path. So if I have:

RewriteBase /blah/
RewriteRule ^foo$ bar.php [L]

in "subsubdir", going to http://example.com/subdir2/subsubdir/foo will actually serve me http://example.com/blah/bar.php. The "bar.php" is added to the end of the base. In practice, this example is usually not what you want, because you can't have multiple bases in the same directory container or htaccess file.

In most cases, it's used like this:

RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]

where those rules would be in the "subdir1" directory and

RewriteBase /subdir2/subsubdir/
RewriteRule ^foo$ bar.php [L]

would be in the "subsubdir" directory.

This partly allows you to make your rules portable, so you can drop them in any directory and only need to change the base instead of a bunch of rules. For example if you had:

RewriteEngine On
RewriteRule ^foo$ /subdir1/bar.php [L]
RewriteRule ^blah1$ /subdir1/blah.php?id=1 [L]
RewriteRule ^blah2$ /subdir1/blah2.php [L]
...

such that going to http://example.com/subdir1/foo will serve http://example.com/subdir1/bar.php etc. And say you decided to move all of those files and rules to the "subsubdir" directory. Instead of changing every instance of /subdir1/ to /subdir2/subsubdir/, you could have just had a base:

RewriteEngine On
RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]
RewriteRule ^blah1$ blah.php?id=1 [L]
RewriteRule ^blah2$ blah2.php [L]
...

And then when you needed to move those files and the rules to another directory, just change the base:

RewriteBase /subdir2/subsubdir/

and that's it.

How to create a GUID / UUID

This creates a version 4 UUID (created from pseudo random numbers):

function uuid()
{
   var chars = '0123456789abcdef'.split('');

   var uuid = [], rnd = Math.random, r;
   uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
   uuid[14] = '4'; // version 4

   for (var i = 0; i < 36; i++)
   {
      if (!uuid[i])
      {
         r = 0 | rnd()*16;

         uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
      }
   }

   return uuid.join('');
}

Here is a sample of the UUIDs generated:

682db637-0f31-4847-9cdf-25ba9613a75c
97d19478-3ab2-4aa1-b8cc-a1c3540f54aa
2eed04c9-2692-456d-a0fd-51012f947136

require is not defined? Node.js

This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

Working Copy Locked

Is your BitLocker disk encryption running? In my case, it locked the whole drive of the disk for encryption, and SVN failed with this error.

C++ preprocessor __VA_ARGS__ number of arguments

You can stringfy and count tokens:

int countArgs(char *args)
{
  int result = 0;
  int i = 0;

  while(isspace(args[i])) ++i;
  if(args[i]) ++result;

  while(args[i]) {
    if(args[i]==',') ++result;
    else if(args[i]=='\'') i+=2;
    else if(args[i]=='\"') {
      while(args[i]) {
        if(args[i+1]=='\"' && args[i]!='\\') {
          ++i;
          break;
        }
        ++i;
      }
    }
    ++i;
  }

  return result;
}

#define MACRO(...) \
{ \
  int count = countArgs(#__VA_ARGS__); \
  printf("NUM ARGS: %d\n",count); \
}

Adding up BigDecimals using Streams

You can sum up the values of a BigDecimal stream using a reusable Collector named summingUp:

BigDecimal sum = bigDecimalStream.collect(summingUp());

The Collector can be implemented like this:

public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
    return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}

Valid to use <a> (anchor tag) without href attribute?

The <a>nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<a name="foo">) and linked anchors (<a href="#foo">).

The named anchor format is less commonly used, as the fragment identifier is now used to specify an [id] attribute (although for backwards compatibility you can still specify [name] attributes). An <a> element without an [href] attribute is still valid.

As far as semantics and styling is concerned, the <a> element isn't a link (:link) unless it has an [href] attribute. A side-effect of this is that an <a> element without [href] won't be in the tabbing order by default.

The real question is whether the <a> element alone is an appropriate representation of a <button>. On a semantic level, there is a distinct difference between a link and a button.

A button is something that when clicked causes an action to occur.

A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (#foo) or moving to a new document in the case of urls (/bar).

As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.

If you're concerned about the semantics and accessibility of using an <a> element (or <span>, or <div>) as a button, you should add the following attributes:

<a role="button" tabindex="0" ...>...</a>

The button role tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.

For <span> and <div> elements, you may want to add JavaScript key listeners for Space or Enter to trigger the click event. <a href> and <button> elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the click trigger to a different key. For example, a "help" button in a web app might be bound to F1.

Repeat a string in JavaScript a number of times

Array(10).fill('a').join('')

Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.

How to create a laravel hashed password

If you want to understand how excatly laravel works you can review the complete class on Github: https://github.com/illuminate/hashing/blob/master/BcryptHasher.php

But basically there are Three PHP methods involved on that:

$pasword = 'user-password';
// To create a valid password out of laravel Try out!
$cost=10; // Default cost
$password = password_hash($pasword, PASSWORD_BCRYPT, ['cost' => $cost]);

// To validate the password you can use
$hash = '$2y$10$NhRNj6QF.Bo6ePSRsClYD.4zHFyoQr/WOdcESjIuRsluN1DvzqSHm';

if (password_verify($pasword, $hash)) {
   echo 'Password is valid!';
} else {
   echo 'Invalid password.';
}

//Finally if you have a $hash but you want to know the information about that hash. 
print_r( password_get_info( $password_hash ));

The hashed password is same as laravel 5.x bcrypt password. No need to give salt and cost, it will take its default values.

Those methods has been implemented in the laravel class, but if you want to learn more please review the official documentation: http://php.net/manual/en/function.password-hash.php

How does true/false work in PHP?

This is covered in the PHP documentation for booleans and type comparison tables.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string '0'
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE.

How to sort pandas data frame using values from several columns?

Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:

 import pandas as pd
 df = pd.read_csv('data.csv')
 df.sort_values(ascending=False,inplace=True)

Refer to the official website here.

Uncaught Typeerror: cannot read property 'innerHTML' of null

If the script is in the head of your HTML document, the body of your HTML document has not yet been created by the browser, regardless of what will eventually be there (the same result occurs if your script is in the HTML file but above the element). When your variable tries to find document.getElementById("status") it does not yet exist, and so it returns a value of null. When you then use the variable later in your code, the initial value (null) is used and not the current one, because nothing has updated the variable.

I didn't want to move my script link out of the HTML head, so instead I did this in my JS file:

var idPost //define a global variable
function updateVariables(){
    idPost = document.getElementById("status").innerHTML; //update the global variable
}

And this in the HTML file:

<body onload="updateVariables()">

If you already have an onload function in place, you can just add the additional line to it or call the function.

If you don't want the variable to be global, define it locally in the function that you are trying to run and make sure the function is not called before the page has fully loaded.

The request was aborted: Could not create SSL/TLS secure channel

This one is working for me in MVC webclient

public string DownloadSite(string RefinedLink)
{
    try
    {
        Uri address = new Uri(RefinedLink);

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        using (WebClient webClient = new WebClient())
        {
            var stream = webClient.OpenRead(address);
            using (StreamReader sr = new StreamReader(stream))
            {
                var page = sr.ReadToEnd();

                return page;
            }
        }

    }
    catch (Exception e)
    {
        log.Error("DownloadSite - error Lin = " + RefinedLink, e);
        return null;
    }
}

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"

How can I simulate mobile devices and debug in Firefox Browser?

Most web applications detects mobile devices based on the HTTP Headers.

If your web site also uses HTTP Headers to identify mobile device, you can do the following:

  1. Add Modify Headers plug in to your Firefox browser ( https://addons.mozilla.org/en-US/firefox/addon/modify-headers/ )
  2. Using plugin modify headers:
    • select Headers tab-> select Action 'ADD'
    • to simulate e.g. iPhone add a header with name User-Agent and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
    • click 'Add' button
  3. After that you should be able to see mobile version of you web application in Firefox and use Firebug plugin.

Hope it helps!

Options for initializing a string array

Basic:

string[] myString = new string[]{"string1", "string2"};

or

string[] myString = new string[4];
myString[0] = "string1"; // etc.

Advanced: From a List

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

From StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

How to filter object array based on attributes?

I'm surprised no one has posted the one-line response:

const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...and just so you can read it easier:

const filteredHomes = json.homes.filter( x => 
  x.price <= 1000 && 
  x.sqft >= 500 && 
  x.num_of_beds >=2 && 
  x.num_of_baths >= 2.5
);

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

Determining if an Object is of primitive type

As several people have already said, this is due to autoboxing.

You could create a utility method to check whether the object's class is Integer, Double, etc. But there is no way to know whether an object was created by autoboxing a primitive; once it's boxed, it looks just like an object created explicitly.

So unless you know for sure that your array will never contain a wrapper class without autoboxing, there is no real solution.

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Uncaught TypeError: Cannot read property 'top' of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:

<a href="#examples">Skip to examples</a>

There has to be an element in the page with that id, example:

<div id="examples">Here are the examples</div>

So make sure that each one of the links are matched inside the page with it's corresponding anchor.

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

CSS: How to position two elements on top of each other, without specifying a height?

Here's another solution using display: flex instead of position: absolute or display: grid.

_x000D_
_x000D_
.container_row{_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
  width: 100%;_x000D_
  background-color: rgba(255,0,0,0.5);  // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
  width: 100%;_x000D_
  margin-left: -100%;_x000D_
  background-color: rgba(0,0,255,0.5);  // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
    <div class="layer1">_x000D_
        <span>Lorem ipsum...</span>_x000D_
    </div>_x000D_
    <div class="layer2">_x000D_
        More lorem ipsum..._x000D_
    </div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
    ...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get visitor's location (i.e. country) using geolocation?

You can use ip-api.io to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(xhttp.responseText));
        }
    };
    xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
    xhttp.send();
}

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)
                     console.log(result);
                 });
        });
    });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>