Programs & Examples On #Web developer toolbar

Web Developer Toolbar is a generic term for built-in browser debugging tools, rather than a plugin like Firebug. Most include an interactive console, step-through debugger, network performance logging, CSS editor, and JavaScript function profiling.

Best Way to View Generated Source of Webpage?

I know this is an old post, but I just found this piece of gold. This is old (2006), but still works with IE9. I personnally added a bookmark with this.

Just copy paste this in your browser's address bar:

javascript:void(window.open("javascript:document.open(\"text/plain\");document.write(opener.document.body.parentNode.outerHTML)"))

As for firefox, web developper tool bar does the job. I usually use this, but sometimes, some dirty 3rd party asp.net controls generates differents markups based on the user agent...

EDIT

As Bryan pointed in the comment, some browser remove the javascript: part when copy/pasting in url bar. I just tested and that's the case with IE10.

What does status=canceled for a resource mean in Chrome Developer Tools?

In my case the code to show e-mail client window caused Chrome to stop loading images:

document.location.href = mailToLink;

moving it to $(window).load(function () {...}) instead of $(function () {...}) helped.

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

SQL Server query - Selecting COUNT(*) with DISTINCT

SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE push_number=@push_number 
GROUP BY program_type

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Change route params without reloading in Angular 2

As of RC6 you can do the following to change URL without change state and thereby keeping your route history

    import {OnInit} from '@angular/core';

    import {Location} from '@angular/common'; 
    // If you dont import this angular will import the wrong "Location"

    @Component({
        selector: 'example-component',
        templateUrl: 'xxx.html'
    })
    export class ExampleComponent implements OnInit {
        
        constructor( private location: Location )
        {}

        ngOnInit() {    
            this.location.replaceState("/some/newstate/");
        }
    }

Git log to get commits only for a specific branch

You could try something like this:

#!/bin/bash

all_but()
{
    target="$(git rev-parse $1)"
    echo "$target --not"
    git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
    while read entry
    do
        eval "$entry"

        test "$ref" != "$target" && echo "$ref"
    done
}

git log $(all_but $1)

Or, borrowing from the recipe in the Git User's Manual:

#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )

Pass all variables from one shell script to another?

Adding to the answer of Fatal Error, There is one more way to pass the variables to another shell script.

The above suggested solution have some drawbacks:

  1. using Export : It will cause the variable to be present out of their scope which is not a good design practice.
  2. using Source : It may cause name collisions or accidental overwriting of a predefined variable in some other shell script file which have sourced another file.

There is another simple solution avaiable for us to use. Considering the example posted by you,

test.sh

#!/bin/bash

TESTVARIABLE=hellohelloheloo
./test2.sh "$TESTVARIABLE"

test2.sh

#!/bin/bash

echo $1

output

hellohelloheloo

Also it is important to note that "" are necessary if we pass multiword strings. Taking one more example

master.sh

#!/bin/bash
echo in master.sh
var1="hello world"
sh slave1.sh $var1
sh slave2.sh "$var1"
echo back to master

slave1.sh

#!/bin/bash
echo in slave1.sh
echo value :$1

slave2.sh

#!/bin/bash
echo in slave2.sh
echo value : $1

output

in master.sh
in slave1.sh
value :"hello
in slave2.sh
value :"hello world"

It happens because of the reasons aptly described in this link

Failed to create provisioning profile

Both of these errors arise as a result of a provisioning profile not existing. To create one, simply do the following as suggested in the error message:

  1. Plug in your Apple device
  2. Choose the device from the schemes/simulator menu
  3. Thereafter, provisioning profile will automatically be created

enter image description here

How can I use a local image as the base image with a dockerfile?

Verified: it works well in Docker 1.7.0.

Don't specify --pull=true when running the docker build command

From this thread on reference locally-built image using FROM at dockerfile:

If you want use the local image as the base image, pass without the option --pull=true
--pull=true will always attempt to pull a newer version of the image.

How to use Bootstrap in an Angular project?

If you plan on using Bootstrap 4 which is required with the angular-ui team's ng-bootstrap that is mentioned in this thread, you'll want to use this instead (NOTE: you don't need to include the JS file):

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

You can also reference this locally after running npm install [email protected] --save by pointing to the file in your styles.scss file, assuming you're using SASS:

@import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';

Validating URL in Java

Use the android.webkit.URLUtil on android:

URLUtil.isValidUrl(URL_STRING);

Note: It is just checking the initial scheme of URL, not that the entire URL is valid.

How to extract .war files in java? ZIP vs JAR

Like you said, a jar is a zip file (not a special type, but just a plain old zip), so either library could be made to work. The reasoning is that the average person, seeing a *.zip extension, tends to unzip it. Since the app server wants it unzipped, a simple rename keeps people from unzipping it simply out of habit. Likewise, *.war file also should remain uncompressed.

java.util.jar basically just adds additional functionality to java.util.zip with very little extra overhead. Let the java.util.jar be a helper in posting, etc... and use it.

How to get date in BAT file

This will give you DD MM YYYY YY HH Min Sec variables and works on any Windows machine from XP Pro and later.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow

So i used:

stage ('Starting ART job') {
    build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}

Json.net serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Animal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

How to write lists inside a markdown table?

Yes, you can merge them using HTML. When I create tables in .md files from Github, I always like to use HTML code instead of markdown.

Github Flavored Markdown supports basic HTML in .md file. So this would be the answer:

Markdown mixed with HTML:

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|

Or pure HTML:

<table>
  <tbody>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
    <tr>
      <td>
        <ul>
          <li>item1</li>
          <li>item2</li>
        </ul>
      </td>
      <td align="center">See the list</td>
      <td align="right">from the first column</td>
    </tr>
  </tbody>
</table>

This is how it looks on Github:

How to prevent page scrolling when scrolling a DIV element?

Use below CSS property overscroll-behavior: contain; to child element

How can I pair socks from a pile efficiently?

Pick up a first sock and place it on a table. Now pick another sock; if it matches the first picked, place it on top of the first. If not, place it on the table a small distance from the first. Pick a third sock; if it matches either of the previous two, place it on top of them or else place it a small distance from the third. Repeat until you have picked up all the socks.

Printing HashMap In Java

A simple way to see the key value pairs:

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(Arrays.asList(map)); // method 1
System.out.println(Collections.singletonList(map)); // method 2

Both method 1 and method 2 output this:

[{b=2, a=1}]

Angular2 - Radio Button Binding

Note - radio button binding is now a supported feature in RC4 onwards - see this answer

Radio button example using custom RadioControlValueAccessor similar to CheckboxControlValueAccessor (Updated with Angular 2 rc-1)

App.ts

import {Component} from "@angular/core";
import {FORM_DIRECTIVES} from "@angular/common";
import {RadioControlValueAccessor} from "./radio_value_accessor";
import {bootstrap} from '@angular/platform-browser-dynamic';

@Component({
    selector: "my-app",
    templateUrl: "template.html",
    directives: [FORM_DIRECTIVES, RadioControlValueAccessor]
})
export class App {

    model;

    constructor() {
        this.model = {
            sex: "female"
        };
    }
}

template.html

<div>
    <form action="">
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="male">Male<br>
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="female">Female
    </form>

    <input type="button" value="select male" (click)="model.sex='male'">
    <input type="button" value="select female" (click)="model.sex='female'">
    <div>Selected Radio: {{model.sex}}</div>
</div>

radio_value_accessor.ts

import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/common';

export const RADIO_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioControlValueAccessor),
    multi: true
};

@Directive({
   selector:
       'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]',
   host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
   bindings: [RADIO_VALUE_ACCESSOR]
})
export class RadioControlValueAccessor implements ControlValueAccessor {
   onChange = (_) => {};
   onTouched = () => {};

   constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

   writeValue(value: any): void {
       this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value);
   }
   registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; }
   registerOnTouched(fn: () => {}): void { this.onTouched = fn; }
}

Source : https://github.com/angular2-school/angular2-radio-button

Plunker live demo : http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview

Not showing placeholder for input type="date" field

I'm surprised there's only one answer with an approach similar to the one I used.
I got the inspiration from @Dtipson's comment on @Mumthezir VP's answer.

I use two inputs for this, one is a fake input with type="text" on which I set the placeholder, the other one is the real field with type="date".
On the mouseenter event on their container, I hide the fake input and show the real one, and I do the opposite on the mouseleave event. Obviously, I leave the real input visibile if it has a value set on it.
I wrote the code to use pure Javascript but if you use jQuery (I do) it's very easy to "convert" it.

_x000D_
_x000D_
// "isMobile" function taken from this reply:_x000D_
// https://stackoverflow.com/a/20293441/3514976_x000D_
function isMobile() {_x000D_
  try { document.createEvent("TouchEvent"); return true; }_x000D_
  catch(e) { return false; }_x000D_
}_x000D_
_x000D_
var deviceIsMobile = isMobile();_x000D_
_x000D_
function mouseEnterListener(event) {_x000D_
  var realDate = this.querySelector('.real-date');_x000D_
  // if it has a value it's already visible._x000D_
  if(!realDate.value) {_x000D_
    this.querySelector('.fake-date').style.display = 'none';_x000D_
    realDate.style.display = 'block';_x000D_
  }_x000D_
}_x000D_
_x000D_
function mouseLeaveListener(event) {_x000D_
  var realDate = this.querySelector('.real-date');_x000D_
  // hide it if it doesn't have focus (except_x000D_
  // on mobile devices) and has no value._x000D_
  if((deviceIsMobile || document.activeElement !== realDate) && !realDate.value) {_x000D_
    realDate.style.display = 'none';_x000D_
    this.querySelector('.fake-date').style.display = 'block';_x000D_
  }_x000D_
}_x000D_
_x000D_
function fakeFieldActionListener(event) {_x000D_
  event.preventDefault();_x000D_
  this.parentElement.dispatchEvent(new Event('mouseenter'));_x000D_
  var realDate = this.parentElement.querySelector('.real-date');_x000D_
  // to open the datepicker on mobile devices_x000D_
  // I need to focus and then click on the field._x000D_
  realDate.focus();_x000D_
  realDate.click();_x000D_
}_x000D_
_x000D_
var containers = document.getElementsByClassName('date-container');_x000D_
for(var i = 0; i < containers.length; ++i) {_x000D_
  var container = containers[i];_x000D_
  _x000D_
  container.addEventListener('mouseenter', mouseEnterListener);_x000D_
  container.addEventListener('mouseleave', mouseLeaveListener);_x000D_
  _x000D_
  var fakeDate = container.querySelector('.fake-date');_x000D_
  // for mobile devices, clicking (tapping)_x000D_
  // on the fake input must show the real one._x000D_
  fakeDate.addEventListener('click', fakeFieldActionListener);_x000D_
  // let's also listen to the "focus" event_x000D_
  // in case it's selected using a keyboard._x000D_
  fakeDate.addEventListener('focus', fakeFieldActionListener);_x000D_
  _x000D_
  var realDate = container.querySelector('.real-date');_x000D_
  // trigger the "mouseleave" event on the_x000D_
  // container when the value changes._x000D_
  realDate.addEventListener('change', function() {_x000D_
    container.dispatchEvent(new Event('mouseleave'));_x000D_
  });_x000D_
  // also trigger the "mouseleave" event on_x000D_
  // the container when the input loses focus._x000D_
  realDate.addEventListener('blur', function() {_x000D_
    container.dispatchEvent(new Event('mouseleave'));_x000D_
  });_x000D_
}
_x000D_
.real-date {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
/* a simple example of css to make _x000D_
them look like it's the same element */_x000D_
.real-date, _x000D_
.fake-date {_x000D_
  width: 200px;_x000D_
  height: 20px;_x000D_
  padding: 0px;_x000D_
}
_x000D_
<div class="date-container">_x000D_
  <input type="text" class="fake-date" placeholder="Insert date">_x000D_
  <input type="date" class="real-date">_x000D_
</div>
_x000D_
_x000D_
_x000D_

I tested this also on an Android phone and it works, when the user taps on the field the datepicker is shown. The only thing is, if the real input had no value and the user closes the datepicker without choosing a date, the input will remain visible until they tap outside of it. There's no event to listen to to know when the datepicker closes so I don't know how to solve that.

I don't have an iOS device to test it on.

Convert python datetime to epoch with strftime

import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())

Error: The 'brew link' step did not complete successfully

Had been wrecking my head on symlinking node .. and nothing seemed to work...but finally what worked is setting the right permissions . This 'sudo chown -R $(whoami) /usr/local' did the work for me.

How to set the opacity/alpha of a UIImage?

I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

SQL Server ORDER BY date and nulls last

According to Itzik Ben-Gan, author of T-SQL Fundamentals for MS SQL Server 2012, "By default, SQL Server sorts NULL marks before non-NULL values. To get NULL marks to sort last, you can use a CASE expression that returns 1 when the" Next_Contact_Date column is NULL, "and 0 when it is not NULL. Non-NULL marks get 0 back from the expression; therefore, they sort before NULL marks (which get 1). This CASE expression is used as the first sort column." The Next_Contact_Date column "should be specified as the second sort column. This way, non-NULL marks sort correctly among themselves." Here is the solution query for your example for MS SQL Server 2012 (and SQL Server 2014):

ORDER BY 
   CASE 
        WHEN Next_Contact_Date IS NULL THEN 1
        ELSE 0
   END, Next_Contact_Date;

Equivalent code using IIF syntax:

ORDER BY 
   IIF(Next_Contact_Date IS NULL, 1, 0),
   Next_Contact_Date;

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

How to delete a character from a string using Python

Here's what I did to slice out the "M":

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]

Maximum number of rows in an MS Access database engine table?

Here's my attempt:

I created a single-column (INTEGER) table with no key:

CREATE TABLE a (a INTEGER NOT NULL);

Inserted integers in sequence starting at 1.

I stopped it (arbitrarily after many hours) when it had inserted 65,632,875 rows. The file size was 1,029,772 KB.

I compacted the file which reduced it very slightly to 1,029,704 KB.

I added a PK:

ALTER TABLE a ADD CONSTRAINT p PRIMARY KEY (a);

which increased the file size to 1,467,708 KB.

This suggests the maximum is somewhere around the 80 million mark.

Can a PDF file's print dialog be opened with Javascript?

If you are using the prawn gem for Ruby on Rails to generate your PDF, you can use the following additional gem to active the print dialog:

prawn-print

Determine Whether Integer Is Between Two Other Integers?

Your code snippet,

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

actually checks if number is larger than both 10000 and 30000.

Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:

if 10000 <= number <= 30000:
    print ("you have to pay 5% taxes")

This Python feature is further described in the Python documentation.

How to avoid "Permission denied" when using pip with virtualenv

While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.

You can also copy packages installed on global python to virtualenv.

cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/

Local dependency in package.json

Master project

Here is the package.json you will use for the master project:

"dependencies": {
    "express": "*",
    "somelocallib": "file:./somelocallib"
}

There, ./somelocallib is the reference to the library folder as relative to the master project package.json.

Reference: https://docs.npmjs.com/files/package.json#local-paths


Sub project

Handle your library dependencies.

In addition to running npm install, you will need to run (cd node_modules/somelocallib && npm install).

This is a known bug with NPM.

Reference: https://github.com/npm/npm/issues/1341 (seeking a more up-to-date reference)


Notes for Docker

Check in your master package.lock and your somelocallib/package.lock into your source code manager.

Then in your Dockerfile use:

FROM node:10
WORKDIR /app
# ...
COPY ./package.json ./package-lock.json ./
COPY somelocallib somelocallib
RUN npm ci
RUN (cd node_modules/zkp-utils/ && npm ci)
# ...

I use parenthesis in my (cd A && B) constructs to make the operation idempotent.

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Symbolicating iPhone App Crash Reports

atos is being deprecated so if you are running OSX 10.9 or later you may need to run

xcrun atos

Warning: /usr/bin/atos is moving and will be removed from a future OS X release. It is now available in the Xcode developer tools to be invoked via: xcrun atos

How to import keras from tf.keras in Tensorflow?

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

In Keras (v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras (v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

Note: TensorFlow Version is 1.9

Is there a way to make npm install (the command) to work behind proxy?

Use below command at cmd or GIT Bash or other prompt

$ npm config set proxy "http://192.168.1.101:4128"

$ npm config set https-proxy "http://192.168.1.101:4128"

where 192.168.1.101 is proxy ip and 4128 is port. change according to your proxy settings. its works for me.

Custom Authentication in ASP.Net-Core

From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication

In Startup.cs :

Add below lines to ConfigureServices method :

public void ConfigureServices(IServiceCollection services)
{

services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
    });

    services.AddMvc();

    // authentication 
    services.AddAuthentication(options =>
    {
       options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });

    services.AddTransient(
        m => new UserManager(
            Configuration
                .GetValue<string>(
                    DEFAULT_CONNECTIONSTRING //this is a string constant
                )
            )
        );
     services.AddDistributedMemoryCache();
}

keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize] , they well force redirect to /Account/Login url.

Add below lines to Configure method :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler(ERROR_URL);
    }
     app.UseStaticFiles();
     app.UseAuthentication();
     app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: DEFAULT_ROUTING);
    });
}

Create your UserManager class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):

public class UserManager
{
    string _connectionString;

    public UserManager(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    {
        using (var con = new SqlConnection(_connectionString))
        {
            var queryString = "sp_user_login";
            var dbUserData = con.Query<UserDbModel>(
                queryString,
                new
                {
                    UserEmail = user.UserEmail,
                    UserPassword = user.UserPassword,
                    UserCellphone = user.UserCellphone
                },
                commandType: CommandType.StoredProcedure
            ).FirstOrDefault();

            ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
    }

    public async void SignOut(HttpContext httpContext)
    {
        await httpContext.SignOutAsync();
    }

    private IEnumerable<Claim> GetUserClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
        claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
        claims.AddRange(this.GetUserRoleClaims(user));
        return claims;
    }

    private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
        return claims;
    }
}

Then maybe you have an AccountController which has a Login Action that should look like below :

public class AccountController : Controller
{
    UserManager _userManager;

    public AccountController(UserManager userManager)
    {
        _userManager = userManager;
    }

    [HttpPost]
    public IActionResult LogIn(LogInViewModel form)
    {
        if (!ModelState.IsValid)
            return View(form);
         try
        {
            //authenticate
            var user = new UserDbModel()
            {
                UserEmail = form.Email,
                UserCellphone = form.Cellphone,
                UserPassword = form.Password
            };
            _userManager.SignIn(this.HttpContext, user);
             return RedirectToAction("Search", "Home", null);
         }
         catch (Exception ex)
         {
            ModelState.AddModelError("summary", ex.Message);
            return View(form);
         }
    }
}

Now you are able to use [Authorize] annotation on any Action or Controller.

Feel free to comment any questions or bug's.

How to create custom spinner like border around the spinner with down triangle on the right side?

Spinner

<Spinner
    android:id="@+id/To_Units"
    style="@style/spinner_style" />

style.xml

    <style name="spinner_style">
          <item name="android:layout_width">match_parent</item>
          <item name="android:layout_height">wrap_content</item>
          <item name="android:background">@drawable/gradient_spinner</item>
          <item name="android:layout_margin">10dp</item>
          <item name="android:paddingLeft">8dp</item>
          <item name="android:paddingRight">20dp</item>
          <item name="android:paddingTop">5dp</item>
          <item name="android:paddingBottom">5dp</item>
          <item name="android:popupBackground">#DFFFFFFF</item>
     </style>

gradient_spinner.xml (in drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
            <item><shape>
                    <gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />

                    <stroke android:width="1dp" android:color="#000000" />

                    <corners android:radius="4dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape></item>
            <item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
            </item>
        </layer-list></item>

</selector>  

@drawable/spinner_arrow is your bottom right corner image

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

Installing PG gem on OS X - failure to build native extension

i got same problem and i solved

gem update --system 3.0.6

Checking if a variable is defined?

defined? is great, but if you are in a Rails environment you can also use try, especially in cases where you want to check a dynamic variable name:

foo = 1
my_foo = "foo"
my_bar = "bar"
try(:foo)        # => 1
try(:bar)        # => nil
try(my_foo)      # => 1
try(my_bar)      # => nil

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

How do I use properly CASE..WHEN in MySQL

CASE case_value
    WHEN when_value THEN statements
    [WHEN when_value THEN statements]
    ELSE statements
END 

Or:

CASE
WHEN <search_condition> THEN statements
[WHEN <search_condition> THEN statements] 
ELSE statements
END 

here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else

SELECT
   CASE course_enrollment_settings.base_price
    WHEN course_enrollment_settings.base_price = 0      THEN 1

should be

SELECT
   CASE 
    WHEN course_enrollment_settings.base_price = 0      THEN 1

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

How does strtok() split the string into tokens in C?

strtok maintains a static, internal reference pointing to the next available token in the string; if you pass it a NULL pointer, it will work from that internal reference.

This is the reason strtok isn't re-entrant; as soon as you pass it a new pointer, that old internal reference gets clobbered.

How to animate the change of image in an UIImageView?

Swift 5 extension:

extension UIImageView{
    func setImage(_ image: UIImage?, animated: Bool = true) {
        let duration = animated ? 0.3 : 0.0
        UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: {
            self.image = image
        }, completion: nil)
    }
}
 

How to remove a field completely from a MongoDB document?

db.example.updateMany({},{"$unset":{"tags.words":1}})

We can also use this to update multiple documents.

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

How to compress an image via Javascript in the browser?

I see two things missing from the other answers:

  • canvas.toBlob (when available) is more performant than canvas.toDataURL, and also async.
  • the file -> image -> canvas -> file conversion loses EXIF data; in particular, data about image rotation commonly set by modern phones/tablets.

The following script deals with both points:

// From https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob, needed for Safari:
if (!HTMLCanvasElement.prototype.toBlob) {
    Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value: function(callback, type, quality) {

            var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
                len = binStr.length,
                arr = new Uint8Array(len);

            for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i);
            }

            callback(new Blob([arr], {type: type || 'image/png'}));
        }
    });
}

window.URL = window.URL || window.webkitURL;

// Modified from https://stackoverflow.com/a/32490603, cc by-sa 3.0
// -2 = not jpeg, -1 = no data, 1..8 = orientations
function getExifOrientation(file, callback) {
    // Suggestion from http://code.flickr.net/2012/06/01/parsing-exif-client-side-using-javascript-2/:
    if (file.slice) {
        file = file.slice(0, 131072);
    } else if (file.webkitSlice) {
        file = file.webkitSlice(0, 131072);
    }

    var reader = new FileReader();
    reader.onload = function(e) {
        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8) {
            callback(-2);
            return;
        }
        var length = view.byteLength, offset = 2;
        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    callback(-1);
                    return;
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112) {
                        callback(view.getUint16(offset + (i * 12) + 8, little));
                        return;
                    }
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        callback(-1);
    };
    reader.readAsArrayBuffer(file);
}

// Derived from https://stackoverflow.com/a/40867559, cc by-sa
function imgToCanvasWithOrientation(img, rawWidth, rawHeight, orientation) {
    var canvas = document.createElement('canvas');
    if (orientation > 4) {
        canvas.width = rawHeight;
        canvas.height = rawWidth;
    } else {
        canvas.width = rawWidth;
        canvas.height = rawHeight;
    }

    if (orientation > 1) {
        console.log("EXIF orientation = " + orientation + ", rotating picture");
    }

    var ctx = canvas.getContext('2d');
    switch (orientation) {
        case 2: ctx.transform(-1, 0, 0, 1, rawWidth, 0); break;
        case 3: ctx.transform(-1, 0, 0, -1, rawWidth, rawHeight); break;
        case 4: ctx.transform(1, 0, 0, -1, 0, rawHeight); break;
        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
        case 6: ctx.transform(0, 1, -1, 0, rawHeight, 0); break;
        case 7: ctx.transform(0, -1, -1, 0, rawHeight, rawWidth); break;
        case 8: ctx.transform(0, -1, 1, 0, 0, rawWidth); break;
    }
    ctx.drawImage(img, 0, 0, rawWidth, rawHeight);
    return canvas;
}

function reduceFileSize(file, acceptFileSize, maxWidth, maxHeight, quality, callback) {
    if (file.size <= acceptFileSize) {
        callback(file);
        return;
    }
    var img = new Image();
    img.onerror = function() {
        URL.revokeObjectURL(this.src);
        callback(file);
    };
    img.onload = function() {
        URL.revokeObjectURL(this.src);
        getExifOrientation(file, function(orientation) {
            var w = img.width, h = img.height;
            var scale = (orientation > 4 ?
                Math.min(maxHeight / w, maxWidth / h, 1) :
                Math.min(maxWidth / w, maxHeight / h, 1));
            h = Math.round(h * scale);
            w = Math.round(w * scale);

            var canvas = imgToCanvasWithOrientation(img, w, h, orientation);
            canvas.toBlob(function(blob) {
                console.log("Resized image to " + w + "x" + h + ", " + (blob.size >> 10) + "kB");
                callback(blob);
            }, 'image/jpeg', quality);
        });
    };
    img.src = URL.createObjectURL(file);
}

Example usage:

inputfile.onchange = function() {
    // If file size > 500kB, resize such that width <= 1000, quality = 0.9
    reduceFileSize(this.files[0], 500*1024, 1000, Infinity, 0.9, blob => {
        let body = new FormData();
        body.set('file', blob, blob.name || "file.jpg");
        fetch('/upload-image', {method: 'POST', body}).then(...);
    });
};

Remove HTML Tags from an NSString on the iPhone

This NSString category uses the NSXMLParser to accurately remove any HTML tags from an NSString. This is a single .m and .h file that can be included into your project easily.

https://gist.github.com/leighmcculloch/1202238

You then strip html by doing the following:

Import the header:

#import "NSString_stripHtml.h"

And then call stripHtml:

NSString* mystring = @"<b>Hello</b> World!!";
NSString* stripped = [mystring stripHtml];
// stripped will be = Hello World!!

This also works with malformed HTML that technically isn't XML.

How can I find the number of days between two Date objects in Ruby?

Subtract the beginning date from the end date:

endDate - beginDate 

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

No, the errors occurs only after the Intelephense extension is automatically updated.

To solve the problem, you can downgrade it to the previous version by click "Install another version" in the Intelephense extension. There are no errors on version 1.2.3.

Homebrew: Could not symlink, /usr/local/bin is not writable

I found same problem, we can resolve in three steps:-

Step 1

sudo chown -R $(whoami) $(brew --prefix)/*

Step 2

brew doctor

Step 3

brew prune

If you still get any linking problem, lets say for mysql, just write

brew link mysql

This will work.

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

ECMAScript 6 class destructor

"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."

Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.

For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.

// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
    $scope.listenerCleanup = [];
    $scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}

// Remove event listeners when the controller is destroyed
function onDestroy(){
    $scope.listenerCleanup.forEach( remove => remove() );
}


Python dictionary: Get list of values for list of keys

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

How to copy part of an array to another array in C#?

Note: I found this question looking for one of the steps in the answer to how to resize an existing array.

So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.

For anyone else finding this question looking for the same thing I was, it is very simple:

Array.Resize<T>(ref arrayVariable, newSize);

where T is the type, i.e. where arrayVariable is declared:

T[] arrayVariable;

That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.

See the MSDN article for more.

Constructor of an abstract class in C#

You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

How to read AppSettings values from a .json file in ASP.NET Core

With the latest iteration of netcoreapp 3.1 out, you can do this pretty simply without any third-party dependencies.

I created a gist for this, but you can use this class to read a JSON file and return dynamic properties.

using System.Text.Json;
using System.IO;

class ConfigurationLoader
{

    private dynamic configJsonData;
    public ConfigurationLoader Load(string configFilePath = "appsettings.json")
    {
        var appSettings = File.ReadAllText(configFilePath);
        this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
        return this;
    }

    public dynamic GetProperty(string key)
    {
        var properties = key.Split(".");
        dynamic property = this.configJsonData;
        foreach (var prop in properties)
        {
            property = property.GetProperty(prop);
        }

        return property;
    }
}

I specifically made this so I could use an appconfig.json in my dotnet console application. I just put this in my Program.Main function:

var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));

And this will return a dynamic object for the property. (A JsonElement if it's not a primitive). My appsettings.json file looks like this:

{
  "Environment": {
    "Token": "abc-123",
    "Name": "Production"
  }
}

How can I set the 'backend' in matplotlib in Python?

Before starting python, you can do in bash

export MPLBACKEND=TkAgg

Class JavaLaunchHelper is implemented in two places

I have found the other workaround: to exclude libinstrument.dylib from project path. To do so, go to the Preferences -> Build, Execution and Deployment -> Compiler -> Excludes -> + and here add file by the path in error message.

How to clear File Input

this code works for all browsers and all inputs.

$('#your_target_input').attr('value', '');

PG COPY error: invalid input syntax for integer

this ought to work without you modifying the source csv file:

alter table people alter column age type text;
copy people from '/tmp/people.csv' with csv;

Overwriting my local branch with remote branch

What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:

git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch

Then if you're sure you don't want anything from your old branch, remove it:

git branch -D branch-old

But usually I leave the old branch around locally, just in case I had something in there.

Ruby on Rails: how to render a string as HTML?

Or you can try CGI.unescapeHTML method.

CGI.unescapeHTML "&lt;p&gt;This is a Paragraph.&lt;/p&gt;"
=> "<p>This is a Paragraph.</p>"

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

Where does Java's String constant pool live, the heap or the stack?

As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.

It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931

And in Java 8 Hotspot, Permanent Generation has been completely removed.

Most efficient way to concatenate strings?

Following may be one more alternate solution to concatenate multiple strings.

String str1 = "sometext";
string str2 = "some other text";

string afterConcate = $"{str1}{str2}";

string interpolation

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

How to redraw DataTable with new data

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

There is a history in C of doing things like:

while (*a++ = *b++);

to copy a string, perhaps this is the source of the excessive trickery he is referring to.

And there's always the question of what

++i = i++;

or

i = i++ + ++i;

actually do. It's defined in some languages, and in other's there's no guarantee what will happen.

Those examples aside, I don't think there's anything more idiomatic than a for loop that uses ++ to increment. In some cases you could get away with a foreach loop, or a while loop that checked a different condtion. But contorting your code to try and avoid using incrementing is ridiculous.

CREATE DATABASE permission denied in database 'master' (EF code-first)

The solution to this problem is as simple as eating a piece of cake.This issue generally arises when your user credentials change and SQL server is not able to identify you .No need to uninstall the existing SQL server instance .You can simply install a new instance with a new instance name . Lets say if your last instance name was 'Sqlexpress' , so this time during installation , name your instance as 'Sqlexpress1' . Also don't forget to select the mix mode (i.e Sql Server Authentication & Windows Authentication) during the installation and provide a system admin password which will be handy if such a problem occurs in future. This solution will definitely resolve this issue. Thanks..

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

How can I disable selected attribute from select2() dropdown Jquery?

I'm disabling select2 with:

$('select').select2("enable",false);

And enabling it with

$('select').select2("enable");

pass array to method Java

You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)

make *** no targets specified and no makefile found. stop

Try

make clean
./configure --with-option=/path/etc
make && make install

How do I grab an INI value within a shell script?

You may use crudini tool to get ini values, e.g.:

DATABASE_VERSION=$(crudini --get parameters.ini '' database_version)

Using Eloquent ORM in Laravel to perform search of database using LIKE

FYI, the list of operators (containing like and all others) is in code:

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
);

disclaimer:

Joel Larson's answer is correct. Got my upvote.

I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.

What is ViewModel in MVC?

If you want to study code how to setup a "Baseline" web application with ViewModels I can advise to download this code on GitHub: https://github.com/ajsaulsberry/BlipAjax. I developed large enterprise applications. When you do this its problematic to setup a good architecture that handles all this "ViewModel" functionality. I think with BlipAjax you will have a very Good "baseline" to start with. Its just a simple website, but great in its simplicity. I like the way they used the English language to point at whats really needed in the application.

Apache won't follow symlinks (403 Forbidden)

First disable selinux (vim /etc/selinux/config)

vim /etc/httpd/conf/httpd.conf edit following lines for symlinks and directory indexing:

documentroot /var/www/html
<directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride None
</directory>

If .htaccess file then AllowOverride all

Import JSON file in React

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

This answer explains more.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I was facing the same issue. I was missing DriverManager.registerDriver() call, before getting the connection using the connection URL and user credentials.

It got fixed on Linux as below:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527//tmp/Test/DB_Name", user, pass);

For Windows:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/Users/Test/DB_Name", user, pass);

Space between border and content? / Border distance from content?

You could try adding an<hr>and styling that. Its a minimal markup change but seems to need less css so that might do the trick.

fiddle:

http://jsfiddle.net/BhxsZ/

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Multiple argument IF statement - T-SQL

Seems to work fine.

If you have an empty BEGIN ... END block you might see

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

Copy folder structure (without files) from one location to another

A python script from Sergiy Kolodyazhnyy posted on Copy only folders not files?:

#!/usr/bin/env python
import os,sys
dirs=[ r for r,s,f in os.walk(".") if r != "."]
for i in dirs:
    os.makedirs(os.path.join(sys.argv[1],i)) 

or from the shell:

python -c 'import os,sys;dirs=[ r for r,s,f in os.walk(".") if r != "."];[os.makedirs(os.path.join(sys.argv[1],i)) for i in dirs]' ~/new_destination

FYI:

Android Studio shortcuts like Eclipse

Using Eclipse key mapping inside Android Studio is the better choice. It will easily adapt to existing key structure. But all the new persons are using new shortcut key structures in Android Studio has. So we will learn and follow Android Studio itself contain shortcuts will help easily interact the team mates.

If you use Android Studio in Max OS X mean to follow the below link. It works for me. https://stackoverflow.com/a/30891985/2219406

SQL Server Insert if not exists

If your clustered index consist from only those fields than the simple, fast and reliable option is to use IGNORE_DUP_KEY

If you create the Clustered index with IGNORE_DUP_KEY ON

Than you can just use:

INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE, @_ASSUNTO, @_DATA)

This should be safe in all cases!

Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

How to overload functions in javascript?

What you are trying to achieve is best done using the function's local arguments variable.

function foo() {
    if (arguments.length === 0) {
        //do something
    }
    if (arguments.length === 1) {
        //do something else
    }
}

foo(); //do something
foo('one'); //do something else

You can find a better explanation of how this works here.

Sound effects in JavaScript / HTML5

I ran into this while programming a musicbox card generator. Started with different libraries but everytime there was a glitch somehow. The lag on normal audio implementation was bad, no multiple plays... eventually ended up using lowlag library + soundmanager:

http://lowlag.alienbill.com/ and http://www.schillmania.com/projects/soundmanager2/

You can check out the implementation here: http://musicbox.grit.it/

I generated wav + ogg files for multi browser plays. This musicbox player works responsive on ipad, iphone, Nexus, mac, pc,... works for me.

When to use an interface instead of an abstract class and vice versa?

An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

Entity Framework: table without primary key

EF does not require a primary key on the database. If it did, you couldn't bind entities to views.

You can modify the SSDL (and the CSDL) to specify a unique field as your primary key. If you don't have a unique field, then I believe you are hosed. But you really should have a unique field (and a PK), otherwise you are going to run into problems later.

Erick

Is there functionality to generate a random character in Java?

In fact mentioned methods don't generate real random char. To generate real random char you should give it a random seed! in example time in millisecond. this code generate 10 random char and then Convert it to String:

import java.util.Random;
public class MyClass {
    public static void main() {

     String randomKey;

    char[] tempArray={0,0,0,0,0,0,0,0,0,0};  //ten characters

    long seed=System.currentTimeMillis();
    Random random=new Random(seed);
    for (int aux=0; aux<10;aux++){

        tempArray[aux]=(char) random.nextInt(255);
        System.out.println(tempArray[aux]);
    }

    randomKey=String.copyValueOf(tempArray);  


      System.out.println(randomKey);
    }
}

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

Please make sure you have typed correct spelling of using script section in view

the correct is

@section scripts{ //your script here}

if you typed @section script{ //your script here} this is wrong.

How to browse localhost on Android device?

Mac OSX Users

If your phone and laptop are on the same wifi:

Go to System Preferences > Network to obtain your IP address

On your mobile browser, type [your IP address]:3000 to access localhost:3000

e.g. 12.45.123.456:3000

How to remove folders with a certain name

Another one:

"-exec rm -rf {} \;" can be replaced by "-delete"

find -type d -name __pycache__ -delete      # GNU find
find . -type d -name __pycache__ -delete    # POSIX find (e.g. Mac OS X)

What are App Domains in Facebook Apps?

It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com

"webxml attribute is required" error in Maven

This is an old question, and there are many answers, most of which will be more or less helpful; however, there is one, very important and still relevant point, which none of the answers touch (providing, instead, different hacks to make build possible), and which, I think, in no way has a less importance.. on the contrary.

According to your log message, you are using Maven, which is a Project Management tool, firmly following the conventions, over configuration principle.

When Maven builds the project:

  1. it expects your project to have a particular directory structure, so that it knows where to expect what. This is called a Maven's Standard Directory Layout;
  2. during the build, it creates also proper directory structure and places files into corresponding locations/directories, and this, in compliance with the Sun Microsystems Directory Structure Standard for Java EE [web] applications.

You may incorporate many things, including maven plugins, changing/reconfiguring project root directory, etc., but better and easier is to follow the default conventions over configuration, according to which, (now is the answer to your problem) there is one simple step that can make your project work: Just place your web.xml under src\main\webapp\WEB-INF\ and try to build the project with mvn package.

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

A C# version of Miroslav Zadravec's code

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

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

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

c++ string array initialization

In C++11 and above, you can also initialize std::vector with an initializer list. For example:

using namespace std; // for example only

for (auto s : vector<string>{"one","two","three"} ) 
    cout << s << endl;

So, your example would become:

void foo(vector<string> strArray){
  // some code
}

vector<string> s {"hi", "there"}; // Works
foo(s); // Works

foo(vector<string> {"hi", "there"}); // also works

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

If you're on Windows and it's not possible to use caching_sha2_password at all, you can do the following:

  1. rerun the MySQL Installer
  2. select "Reconfigure" next to MySQL Server (the top item)
  3. click "Next" until you get to "Authentication Method"
  4. change "Use Strong Password Encryption for Authentication (RECOMMENDED)" to "Use Legacy Authentication Method (Retain MySQL 5.X Compatibility)
  5. click "Next"
  6. enter your Root Account Password in Accounts and Roles, and click "Check"
  7. click "Next"
  8. keep clicking "Next" until you get to "Apply Configuration"
  9. click "Execute"

The Installer will make all the configuration changes needed for you.

Does return stop a loop?

The answer is yes, if you write return statement the controls goes back to to the caller method immediately. With an exception of finally block, which gets executed after the return statement.

and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification

Return Statement definition as per:

Java Docs:

a return statement can be used to branch out of a control flow block and exit the method

MSDN Documentation:

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.

Wikipedia:

A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.

Finding all possible combinations of numbers to reach a given sum

To find the combinations using excel - (its fairly easy). (You computer must not be too slow)

  1. Go to this site
  2. Go to the "Sum to Target" page
  3. Download the "Sum to Target" excel file.

    Follow the directions on the website page.

hope this helps.

Has anyone ever got a remote JMX JConsole to work?

Sushicutta's steps 4-7 can be skipped by adding the following line to step 3:

-Dcom.sun.management.jmxremote.rmi.port=<same port as jmx-remote-port>

e.g. Add to start up parameters:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345
-Dcom.sun.management.jmxremote.rmi.port=12345
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.local.only=false
-Djava.rmi.server.hostname=localhost

For the port forwarding, connect using:

ssh -L 12345:localhost:12345 <username>@<host>

if your host is a stepping stone, simply chain the port forward by running the following on the step stone after the above:

ssh -L 12345:localhost:12345 <username>@<host2>

Mind that the hostname=localhost is needed to make sure the jmxremote is telling the rmi connection to use the tunnel. Otherwise it might try to connect directy and hit the firewall.

How can I make space between two buttons in same div?

I actual ran into the same requirement. I simply used CSS override like this

.navbar .btn-toolbar { margin-top: 0; margin-bottom: 0 }

Move a view up only when the keyboard covers an input field

For Swift 4.2

This code will allow you to control the Y axis moment of the frame for a specific device screen size.

PS: This code will not intelligently move the frame based on the location of TextField.

Create an extension for UIDevice

extension UIDevice {
    enum ScreenType: String {
        case iPhone4_4S = "iPhone 4 or iPhone 4s"
        case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
        case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6s, iPhone 7 or iPhone 8"
        case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6s Plus, iPhone 7 Plus or iPhone 8 Plus"
        case iPhoneX_Xs = "iPhone X, iPhone Xs"
        case iPhoneXR = "iPhone XR"
        case iPhoneXSMax = "iPhone Xs Max"
        case unknown
    }
    var screenType: ScreenType {
        switch UIScreen.main.nativeBounds.height {
        case 960:
            return .iPhone4_4S
        case 1136:
            return .iPhones_5_5s_5c_SE
        case 1334:
            return .iPhones_6_6s_7_8
        case 1920, 2208:
            return .iPhones_6Plus_6sPlus_7Plus_8Plus
        case 1792:
            return .iPhoneXR
        case 2436:
            return .iPhoneX_Xs
        case 2688:
            return .iPhoneXSMax
        default:
            return .unknown
        }
    }
}

Add NotificationObserver on viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

Selector

@objc func keyboardWillShow(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y == 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y -= 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y -= 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y -= 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y -= 70
            default:
                self.view.frame.origin.y -= 150
            }
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y != 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y += 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y += 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y += 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y += 70
            default:
                self.view.frame.origin.y += 150
            }
        }
    }
}

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

How to check if an integer is within a range of numbers in PHP?

The expression:

 ($min <= $value) && ($value <= $max)

will be true if $value is between $min and $max, inclusively

See the PHP docs for more on comparison operators

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

Project has no default.properties file! Edit the project properties to set one

First Close your project.

Open a Text File then Add target=android-your_Api_Level.

Such as: target=android-7 And then Save that file as project.properties Then manually place project.properties file into your Project's Folder and then Reopen you project.

The file generally looks like:

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.

# Project target.
target=android-7

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Use This This Will work For sure

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ProtectedConfigFile {

    private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
    private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
            (byte) 0x10, (byte) 0x12, };

    public static void main(String[] args) throws Exception {
        String originalPassword = "Aman";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
    }

    private static String base64Encode(byte[] bytes) {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Encoder().encode(bytes);
    }

    private static String decrypt(String property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Decoder().decodeBuffer(property);
    }

}

git: patch does not apply

git apply --reverse --reject example.patch

When you created a patch file with the branch names reversed:

ie. git diff feature_branch..master instead of git diff master..feature_branch

ggplot2: sorting a plot

This seems to be what you're looking for:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

The reorder() function will reorder your x axis items according to the value of variable.

pg_config executable not found

There is a lack of answers for windows users. Here is how I solved this issue.

First add the PostgreSQL bin folder into the path variable like this

set PATH=%PATH%;C:\Program Files\PostgreSQL\11\bin

Substitute \11\ with your version of Postgres

next run

pip install pyscopg2

this at least got me to a compiling error.

Update: it looks to be an issue with the psycopg2 library and it’s dependencies not playing nice with python 3.8. https://github.com/psycopg/psycopg2/issues/990

Find duplicate values in R

Here's a data.table solution that will list the duplicates along with the number of duplications (will be 1 if there are 2 copies, and so on - you can adjust that to suit your needs):

library(data.table)
dt = data.table(vocabulary)

dt[duplicated(id), cbind(.SD[1], number = .N), by = id]

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

Based on this SO answer, I just had to change path="*." to path="*" for the added ExtensionlessUrlHandler-Integrated-4.0 in configuration>system.WebServer>handlers in my web.config

Before:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

After:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

How do I get a file's directory using the File object?

I found this more useful for getting the absolute file location.

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());

Controlling fps with requestAnimationFrame?

var time = 0;
var time_framerate = 1000; //in milliseconds

function animate(timestamp) {
  if(timestamp > time + time_framerate) {
    time = timestamp;    

    //your code
  }

  window.requestAnimationFrame(animate);
}

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Force git stash to overwrite added files

Use git checkout instead of git stash apply:

$ git checkout stash -- .
$ git commit

This will restore all the files in the current directory to their stashed version.


If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:

$ git merge --squash --strategy-option=theirs stash

If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using

$ git checkout stash -- <paths...>

or interactively with

$ git checkout -p stash

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

Add characters to a string in Javascript

Simple use text = text + string2

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

Where and why do I have to put the "template" and "typename" keywords?

I am placing JLBorges's excellent response to a similar question verbatim from cplusplus.com, as it is the most succinct explanation I've read on the subject.

In a template that we write, there are two kinds of names that could be used - dependant names and non- dependant names. A dependant name is a name that depends on a template parameter; a non-dependant name has the same meaning irrespective of what the template parameters are.

For example:

template< typename T > void foo( T& x, std::string str, int count )
{
    // these names are looked up during the second phase
    // when foo is instantiated and the type T is known
    x.size(); // dependant name (non-type)
    T::instance_count ; // dependant name (non-type)
    typename T::iterator i ; // dependant name (type)
      
    // during the first phase, 
    // T::instance_count is treated as a non-type (this is the default)
    // the typename keyword specifies that T::iterator is to be treated as a type.

    // these names are looked up during the first phase
    std::string::size_type s ; // non-dependant name (type)
    std::string::npos ; // non-dependant name (non-type)
    str.empty() ; // non-dependant name (non-type)
    count ; // non-dependant name (non-type)
}

What a dependant name refers to could be something different for each different instantiation of the template. As a consequence, C++ templates are subject to "two-phase name lookup". When a template is initially parsed (before any instantiation takes place) the compiler looks up the non-dependent names. When a particular instantiation of the template takes place, the template parameters are known by then, and the compiler looks up dependent names.

During the first phase, the parser needs to know if a dependant name is the name of a type or the name of a non-type. By default, a dependant name is assumed to be the name of a non-type. The typename keyword before a dependant name specifies that it is the name of a type.


Summary

Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.

Seeing the underlying SQL in the Spring JdbcTemplate?

This worked for me with log4j2 and xml parameters:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
    <Properties>
        <Property name="log-path">/some_path/logs/</Property>
        <Property name="app-id">my_app</Property>
    </Properties>

    <Appenders>
        <RollingFile name="file-log" fileName="${log-path}/${app-id}.log"
            filePattern="${log-path}/${app-id}-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>

        <Logger name="org.springframework.jdbc.core" level="trace" additivity="false">
            <appender-ref ref="file-log" />
            <appender-ref ref="console" />
        </Logger>

        <Root level="info" additivity="false">
            <appender-ref ref="file-log" />
            <appender-ref ref="console" />
        </Root>
    </Loggers>

</Configuration>

Result console and file log was:

JdbcTemplate - Executing prepared SQL query
JdbcTemplate - Executing prepared SQL statement [select a, b from c where id = ? ]
StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [my_id], value class [java.lang.String], SQL type unknown

Just copy/past

HTH

Can Android do peer-to-peer ad-hoc networking?

Your answer is Wi-Fi direct which is made available with ICS. Here is a link for explanation in Android doc

Linq where clause compare only date value without time value

Do not simplify the code to avoid "linq translation error": The test consist between a date with time at 0:0:0 and the same date with time at 23:59:59

        iFilter.MyDate1 = DateTime.Today;  // or DateTime.MinValue

        // GET 
        var tempQuery = ctx.MyTable.AsQueryable();

        if (iFilter.MyDate1 != DateTime.MinValue)
        {
            TimeSpan temp24h = new TimeSpan(23,59,59);
            DateTime tempEndMyDate1 = iFilter.MyDate1.Add(temp24h);

            // DO not change the code below, you need 2 date variables...
            tempQuery = tempQuery.Where(w => w.MyDate2 >= iFilter.MyDate1
                                          && w.MyDate2 <= tempEndMyDate1);
        }

        List<MyTable> returnObject = tempQuery.ToList();

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

In Java, how do I check if a string contains a substring (ignoring case)?

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

Get the full URL in PHP

This is the solution for your problem:

//Fetch page URL by this

$url = $_SERVER['REQUEST_URI'];
echo "$url<br />";

//It will print
//fetch host by this

$host=$_SERVER['HTTP_HOST'];
echo "$host<br />";

//You can fetch the full URL by this

$fullurl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;

How can I add a table of contents to a Jupyter / JupyterLab notebook?

JupyterLab ToC instructions

There are already many good answers to this question, but they often require tweaks to work properly with notebooks in JupyterLab. I wrote this answer to detail the possible ways of including a ToC in a notebook while working in and exporting from JupyterLab.

As a side panel

The jupyterlab-toc extension adds the ToC as a side panel that can number headings, collapse sections, and be used for navigation (see gif below for a demo). This extension is included by default since JupyterLab 3.0, in older version you can install it with the following command

jupyter labextension install @jupyterlab/toc

enter image description here


In the notebook as a cell

At the time being, this can either be done manually as in Matt Dancho's answer, or automatically via the toc2 jupyter notebook extension in the classic notebook interface.

First, install toc2 as part of the jupyter_contrib_nbextensions bundle:

conda install -c conda-forge jupyter_contrib_nbextensions

Then, launch JupyterLab, go to Help --> Launch Classic Notebook, and open the notebook in which you want to add the ToC. Click the toc2 symbol in the toolbar to bring up the floating ToC window (see the gif below if you can't find it), click the gear icon and check the box for "Add notebook ToC cell". Save the notebook and the ToC cell will be there when you open it in JupyterLab. The inserted cell is a markdown cell with html in it, it will not update automatically.

The default options of the toc2 can be configured in the "Nbextensions" tab in the classic notebook launch page. You can e.g. choose to number headings and to anchor the ToC as a side bar (which I personally think looks cleaner).

enter image description here


In an exported HTML file

nbconvert can be used to export notebooks to HTML following rules of how to format the exported HTML. The toc2 extension mentioned above adds an export format called html_toc, which can be used directly with nbconvert from the command line (after the toc2 extension has been installed):

jupyter nbconvert file.ipynb --to html_toc
# Append `--ExtractOutputPreprocessor.enabled=False`
# to get a single html file instead of a separate directory for images

Remember that shell commands can be added to notebook cells by prefacing them with an exclamation mark !, so you can stick this line in the last cell of the notebook and always have an HTML file with a ToC generated when you hit "Run all cells" (or whatever output you desire from nbconvert). This way, you could use jupyterlab-toc to navigate the notebook while you are working, and still get ToCs in the exported output without having to resort to using the classic notebook interface (for the purists among us).

Note that configuring the default toc2 options as described above, will not change the format of nbconver --to html_toc. You need to open the notebook in the classic notebook interface for the metadata to be written to the .ipynb file (nbconvert reads the metadata when exporting) Alternatively, you can add the metadata manually via the Notebook tools tab of the JupyterLab sidebar, e.g. something like:

    "toc": {
        "number_sections": false,
        "sideBar": true
    }

If you prefer a GUI-driven approach, you should be able to open the classic notebook and click File --> Save as HTML (with ToC) (although note that this menu item was not available for me).


The gifs above are linked from the respective documentation of the extensions.

How to upgrade Git to latest version on macOS?

After searching for "trouble upgrading git on mac" on Google, I read several posts and attempted the following before resolving the problem by completing step 4:

  1. I updated my terminal path by using the above mention export command. Every time I quit the terminal and restarted it, when I typed git --version the terminal, it still return the older version 1.8.

  2. I followed the README.txt instructions for upgrading to the current version 2.0.1 that comes with the .dmg installer and when I restarted the terminal, still no go.

  3. I looked for /etc/path/ folder as instructed above and the directory called "path" does not exist on my Mac. I am running OS X Mavericks version 10.9.4.

  4. Then I recalled I have Homebrew installed on my Mac and ran the following:

    brew --version
    brew update
    brew search git
    brew install git
    

This finally resolved my problem. If anyone has some insight as to why this worked, further insight would be greatly appreciated. I probably have some left over path settings on my system from working with Ruby last year.

AttributeError: 'tuple' object has no attribute

You return four variables s1,s2,s3,s4 and receive them using a single variable obj. This is what is called a tuple, obj is associated with 4 values, the values of s1,s2,s3,s4. So, use index as you use in a list to get the value you want, in order.

obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
print obj[3] + " is a benefit of functions!"

Enable/disable buttons with Angular

export class ClassComponent implements OnInit {
  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]


checkCurrentLession(current){

 this.classes.forEach((obj)=>{
    if(obj.currentLession == current){
      return true;
    }

  });
  return false;
}


<ul class="table lessonOverview">
        <li>
          <p>Lesson 1</p>
          <button [routerLink]="['/lesson1']" 
             [disabled]="checkCurrentLession(1)" class="primair">
               Start lesson</button>
        </li>
        <li>
          <p>Lesson 2</p>
          <button [routerLink]="['/lesson2']" 
             [disabled]="!checkCurrentLession(2)" class="primair">
               Start lesson</button>
        </li>
     </ul>

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

Regular expression to stop at first match

The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?, .+? etc) are a Perl 5 extension which isn't supported in traditional regular expressions.

If your stopping condition is a single character, the solution is easy; instead of

a(.*?)b

you can match

a[^ab]*b

i.e specify a character class which excludes the starting and ending delimiiters.

In the more general case, you can painstakingly construct an expression like

start(|[^e]|e(|[^n]|n(|[^d])))end

to capture a match between start and the first occurrence of end. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e only if it isn't followed by nd and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.

Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.

How to get xdebug var_dump to show full object/array

I'd like to recommend var_export($array) - it doesn't show types, but it generates syntax you can use in your code :)

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

Insert Data Into Temp Table with Query

SQL Server R2 2008 needs the AS clause as follows:

SELECT * 
INTO #temp
FROM (
    SELECT col1, col2
    FROM table1
) AS x

The query failed without the AS x at the end.


EDIT

It's also needed when using SS2016, had to add as t to the end.

 Select * into #result from (SELECT * FROM  #temp where [id] = @id) as t //<-- as t

Rails DateTime.now without Time

What about Date.today.to_time?

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.

val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
    textView.text = getString(R.string.name)
}

To get the values from the Textview we have to use this method

 val str: String = textView.text.toString()

 println("the value is $str")

Why should a Java class implement comparable?

For example when you want to have a sorted collection or map

jQuery .ready in a dynamically inserted iframe

I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.


var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
    url: url,
    cache: true,
    mimeType: 'application/pdf',
    success: function () {
        // display cached data
        $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
        // hide spinner
        $.mobile.hidePageLoadingMsg();
    }
});

You have to set your http headers correctly as well.


HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

What is the proper way to comment functions in Python?

The correct way to do it is to provide a docstring. That way, help(add) will also spit out your comment.

def add(self):
    """Create a new user.
    Line 2 of comment...
    And so on... 
    """

That's three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn't need to be multiline and double quotes can be replaced by single quotes.

See: PEP 257

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

Jump into interface implementation in Eclipse IDE

Highlight an interface and use Ctrl+T to open "Quick Type Hierarchy".

What are the ways to make an html link open a folder

You can also copy the link address and paste it in a new window to get around the security. This works in chrome and firefox but you may have to add slashes in firefox.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark - NSSecureCoding

The main purpose of "pragma" is for developer reference.enter image description here

You can easily find a method/Function in a vast thousands of coding lines.

Xcode 11+:

Marker Line in Top

// MARK: - Properties

Marker Line in Top and Bottom

// MARK: - Properties - 

Marker Line only in bottom

// MARK: Properties -

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

I just want to add what worked for me, I added height and width to both divs and used bootstrap to make it responsive

   <div class="col-lg-1 mapContainer">
       <div id="map"></div>
   </div>

   #map{
        height: 100%;
        width:100%;
   }
   .mapContainer{
        height:200px;
        width:100%
   }

in order for col-lg-1 to work add bootstrap reference located Here

java.lang.ClassCastException

@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.

Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]; i.e. it was an array object.

Normally, the next steps to solving a problem like this are:

  • examining the stacktrace to figure out which line of which class threw the exception,
  • examining the corresponding source code, to see what the expected type, and
  • tracing back to see where the object with the "wrong" type came from.

Does bootstrap have builtin padding and margin classes?

Bootstrap has many facility of classes to easily style elements if HTML. It includes a various of padding and margin classes for modification of the appearance of the element.

.m-0 { margin:0!important; }
.m-1 { margin:.25rem!important; }
.m-2 { margin:.5rem!important; }
.m-3 { margin:1rem!important; }
.m-4 { margin:1.5rem!important; }
.m-5 { margin:3rem!important; }

.mt-0 { margin-top:0!important; }
.mr-0 { margin-right:0!important; }
.mb-0 { margin-bottom:0!important; }
.ml-0 { margin-left:0!important; }
.mx-0 { margin-left:0!immortant;margin-right:0!immortant; }
.my-0 { margin-top:0!important;margin-bottom:0!important; }

.mt-1 { margin-top:.25rem!important; }
.mr-1 { margin-right:.25rem!important; }
.mb-1 { margin-bottom:.25rem!important; }
.ml-1 { margin-left:.25rem!important; }
.mx-1 { margin-left:.25rem!important;margin-right:.25rem!important; }
.my-1 { margin-top:.25rem!important;margin-bottom:.25rem!important; }

.mt-2 { margin-top:.5rem!important; }
.mr-2 { margin-right:.5rem!important; }
.mb-2 { margin-bottom:.5rem!important; }
.ml-2 { margin-left:.5rem!important; }
.mx-2 { margin-right:.5rem!important;margin-left:.5rem!important; }
.my-2 { margin-top:.5rem!important;margin-bottom:.5rem!important; }

.mt-3 { margin-top:1rem!important; }
.mr-3 { margin-right:1rem!important; }
.mb-3 { margin-bottom:1rem!important; }
.ml-3 { margin-left:1rem!important; }
.mx-3 { margin-right:1rem!important;margin-left:1rem!important; }
.my-3 { margin-bottom:1rem!important;margin-top:1rem!important; }

.mt-4 { margin-top:1.5rem!important; }
.mr-4 { margin-right:1.5rem!important; }
.mb-4 { margin-bottom:1.5rem!important; }
.ml-4 { margin-left:1.5rem!important; }
.mx-4 { margin-right:1.5rem!important;margin-left:1.5rem!important; }
.my-4 { margin-top:1.5rem!important;margin-bottom:1.5rem!important; }

.mt-5 { margin-top:3rem!important; }
.mr-5 { margin-right:3rem!important; }
.mb-5 { margin-bottom:3rem!important; }
.ml-5 { margin-left:3rem!important; }
.mx-5 { margin-right:3rem!important;margin-left:3rem!important; }
.my-5 { margin-top:3rem!important;margin-bottom:3rem!important; }

.mt-auto { margin-top:auto!important; }
.mr-auto { margin-right:auto!important; }
.mb-auto { margin-bottom:auto!important; }
.ml-auto { margin-left:auto!important; }
.mx-auto { margin-right:auto!important;margin-left:auto!important; }
.my-auto { margin-bottom:auto!important;margin-top:auto!important; }

.p-0 { padding:0!important; }
.p-1 { padding:.25rem!important; }
.p-2 { padding:.5rem!important; }
.p-3 { padding:1rem!important; }
.p-4 { padding:1.5rem!important; }
.p-5 { padding:3rem!important; }

.pt-0 { padding-top:0!important; }
.pr-0 { padding-right:0!important; }
.pb-0 { padding-bottom:0!important; }
.pl-0 { padding-left:0!important; }                             
.px-0 { padding-left:0!important;padding-right:0!important; }
.py-0 { padding-top:0!important;padding-bottom:0!important; }

.pt-1 { padding-top:.25rem!important; }         
.pr-1 { padding-right:.25rem!important; }                       
.pb-1 { padding-bottom:.25rem!important; }      
.pl-1 { padding-left:.25rem!important; }                            
.px-1 { padding-left:.25rem!important;padding-right:.25rem!important; }
.py-1 { padding-top:.25rem!important;padding-bottom:.25rem!important; }

.pt-2 { padding-top:.5rem!important; }                                              
.pr-2 { padding-right:.5rem!important; }                                
.pb-2 { padding-bottom:.5rem!important; }               
.pl-2 { padding-left:.5rem!important; }                                             
.px-2 { padding-right:.5rem!important;padding-left:.5rem!important; }
.py-2 { padding-top:.5rem!important;padding-bottom:.5rem!important; }

.pt-3 { padding-top:1rem!important; }                               
.pr-3 { padding-right:1rem!important; }             
.pb-3 { padding-bottom:1rem!important; }                
.pl-3 { padding-left:1rem!important; }                              
.py-3 { padding-bottom:1rem!important;padding-top:1rem!important; }
.px-3 { padding-right:1rem!important;padding-left:1rem!important; }

.pt-4 { padding-top:1.5rem!important; }                             
.pr-4 { padding-right:1.5rem!important; }               
.pb-4 { padding-bottom:1.5rem!important; }              
.pl-4 { padding-left:1.5rem!important; }                                
.px-4 { padding-right:1.5rem!important;padding-left:1.5rem!important; }
.py-4 { padding-top:1.5rem!important;padding-bottom:1.5rem!important; }

.pt-5 { padding-top:3rem!important; }   
.pr-5 { padding-right:3rem!important; } 
.pb-5 { padding-bottom:3rem!important; }    
.pl-5 { padding-left:3rem!important; }  
.px-5 { padding-right:3rem!important;padding-left:3rem!important; }
.py-5 { padding-top:3rem!important;padding-bottom:3rem!important; }

https://jsfiddle.net/ssuryar/x47bca1u/

How to move screen without moving cursor in Vim?

To leave the cursor in the same column when you use Ctrl+D, Ctrl+F, Ctrl+B, Ctrl+U, G, H, M, L, gg

you should define the following option:

:set nostartofline

Can't find how to use HttpContent

Just leaving the way using Microsoft.AspNet.WebApi.Client here.

Example:

var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());

LINQ query to find if items in a list are contained in another list

List<string> l = new List<string> { "@bob.com", "@tom.com" };
List<string> l2 = new List<string> { "[email protected]", "[email protected]" };
List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
foreach (var bob in myboblist)
    Console.WriteLine(bob.ToString());

Defining a percentage width for a LinearLayout?

You can't define width/height/margins/... using percents in your XML. But what you would want to use is the "weight" attribute, which is, IMO, the most similar thing.

Another method would be to set the sizes programmatically after you inflate the layout in your code, by getting the size of your screen and calculating needed margins.

$("#form1").validate is not a function

Had the same issue; validated HTML & found I was missing a name="email" attribute from an <input />. Always validate the HTML to be positive your HTML is valid. After I added it, validate() worked perfectly.

jQuery UI autocomplete with item and id

You need to use the ui.item.label (the text) and ui.item.value (the id) properties

$('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearchID").val()); // get the id from the hidden input
}); 

[Edit] You also asked how to create the multi-dimensional array...

You should be able create the array like so:

var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                     [4,"javascript"], [5,"asp"], [6,"ruby"]];

Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

How to check if a textbox is empty using javascript

Whatever method you choose is not freeing you from performing the same validation on at the back end.

Jquery bind double click and single click separately

Look at the following code

$("#clickMe").click(function (e) {
    var $this = $(this);
    if ($this.hasClass('clicked')){
        alert("Double click");
        //here is your code for double click
        return;
    }else{
         $this.addClass('clicked');
        //your code for single click
         setTimeout(function() { 
                 $this.removeClass('clicked'); },500);
    }//end of else
});

Demo goes here http://jsfiddle.net/cB484/

Where can I download the jar for org.apache.http package?

At the Maven repo, there are samples to add the dependency in maven, sbt, gradle, etc.

https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.11

ie for Maven, you just create a project, for example

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

then look at the pom.xml, then at the library at the dependencies xml element:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.11</version>
</dependency>

For sbt do something like

sbt new scala/hello-world.g8

then edit the build.sbt to add the library

libraryDependencies += "org.apache.httpcomponents" % "httpcore" % "4.4.11"

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

Escape single quote character for use in an SQLite query

Try doubling up the single quotes (many databases expect it that way), so it would be :

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');

Relevant quote from the documentation:

A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. BLOB literals are string literals containing hexadecimal data and preceded by a single "x" or "X" character. ... A literal value can also be the token "NULL".

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

Fragments onResume from back stack

If a fragment is put on backstack, Android simply destroys its view. The fragment instance itself is not killed. A simple way to start should to to listen to the onViewCreated event, an put you "onResume()" logic there.

boolean fragmentAlreadyLoaded = false;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);

        if (savedInstanceState == null && !fragmentAlreadyLoaded) {
            fragmentAlreadyLoaded = true;

            // Code placed here will be executed once
        }

        //Code placed here will be executed even when the fragment comes from backstack
    }

how to apply click event listener to image in android

Try this example.

activity_main.xml:

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

<GridView
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/grid"
    android:background="#fff7ff"
    />

    </LinearLayout>

grid_single.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/grid_image"
        android:layout_width="60dp"
        android:layout_height="60dp"

        >
    </ImageView>

    <TextView
        android:id="@+id/grid_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textSize="9sp"
        android:textColor="#3a0fff">
    </TextView>

</LinearLayout>

CustomGrid.java:

package com.example.lalit.gridtest;

import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

public class CustomGrid extends BaseAdapter {
    private Context mContext;
    private final String[] web;
    private final int[] Imageid;

    public CustomGrid(Context c, String[] web, int[] Imageid) {
        mContext = c;
        this.Imageid = Imageid;
        this.web = web;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return web.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
            textView.setText(web[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

MainActivity.java:

package com.example.lalit.gridtest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    GridView grid;
    String[] web = {
            "Mom",
            "Mahendra",
            "Narayan",
            "Bhai",
            "Deepak",
            "Sanjay",
            "Navdeep",
            "Lovesh",


    };
    int[] imageId = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher

    };

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

        final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
        grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id){

                if (web[position].toString().equals("Mom")) {
                    try {
                        String uri ="te:"+ "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }


                    if (web[position].toString().equals("Mahendra")) {
                        try {
                            String uri = "tel:" + "**********";

                            Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                            startActivity(callIntent);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Your call has failed...",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }


                      if(web[position].toString().equals("Narayan")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


             }
                if(web[position].toString().equals("Bhai")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                if(web[position].toString().equals("Deepak")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }


                if(web[position].toString().equals("Sanjay")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Navdeep")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Lovesh")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                }



        });

    }

    }

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lalit.gridtest" >
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

If you want to change the permissions of an existing file, use chmod (change mode):

$itWorked = chmod ("/yourdir/yourfile", 0777);

If you want all new files to have certain permissions, you need to look into setting your umode. This is a process setting that applies a default modification to standard modes.

It is a subtractive one. By that, I mean a umode of 022 will give you a default permission of 755 (777 - 022 = 755).

But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.

Authenticate Jenkins CI for Github private repository

One thing that got this working for me is to make sure that github.com is in ~jenkins/.ssh/known_hosts.

HTML select dropdown list

This is an old post, but this worked for me

_x000D_
_x000D_
<select>_x000D_
  <option value="" disabled selected>Please select a name...</option> _x000D_
  <option>this</option>_x000D_
  <option>that</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What's the difference between fill_parent and wrap_content?

fill_parent :

A component is arranged layout for the fill_parent will be mandatory to expand to fill the layout unit members, as much as possible in the space. This is consistent with the dockstyle property of the Windows control. A top set layout or control to fill_parent will force it to take up the entire screen.

wrap_content

Set up a view of the size of wrap_content will be forced to view is expanded to show all the content. The TextView and ImageView controls, for example, is set to wrap_content will display its entire internal text and image. Layout elements will change the size according to the content. Set up a view of the size of Autosize attribute wrap_content roughly equivalent to set a Windows control for True.

For details Please Check out this link : http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

converting drawable resource image into bitmap

You probably mean Notification.Builder.setLargeIcon(Bitmap), right? :)

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);

This is a great method of converting resource images into Android Bitmaps.

Android SDK Manager Not Installing Components

For Linux/ubuntu User

  • Why it's happening?
    due to lock icon on some folder(not having read/write access) in
    "/yourpath/android-studio-SDK"

  • Sort and sweet solution
    -Open Terminal (Ctrl +alt +t)
    -copy pest sudo chown -R $USER: $HOME
    -wait for a while.....
    -now Try again to update your SDK

Happy Coding :)

Connect multiple devices to one device via Bluetooth

Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2 in dependency section of your build.gradle .

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

Not the best solution, but for those who are facing LazyInitializationException especially on Serialization this will help. Here you will check lazily initialized properties and setting null to those. For that create the below class

public class RepositoryUtil {
    public static final boolean isCollectionInitialized(Collection<?> collection) {
        if (collection instanceof PersistentCollection)
            return ((PersistentCollection) collection).wasInitialized();
        else 
            return true;
    }   
}

Inside your Entity class which you are having lazily initialized properties add a method like shown below. Add all your lazily loading properties inside this method.

public void checkLazyIntialzation() {
    if (!RepositoryUtil.isCollectionInitialized(yourlazyproperty)) {
        yourlazyproperty= null;
    }

Call this checkLazyIntialzation() method after on all the places where you are loading data.

 YourEntity obj= entityManager.find(YourEntity.class,1L);
  obj.checkLazyIntialzation();

Restart pods when configmap updates in Kubernetes?

Had this problem where the Deployment was in a sub-chart and the values controlling it were in the parent chart's values file. This is what we used to trigger restart:

spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ tpl (toYaml .Values) . | sha256sum }}

Obviously this will trigger restart on any value change but it works for our situation. What was originally in the child chart would only work if the config.yaml in the child chart itself changed:

    checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}

jQuery click anywhere in the page except on 1 div

You can apply click on body of document and cancel click processing if the click event is generated by div with id menu_content, This will bind event to single element and saving binding of click with every element except menu_content

$('body').click(function(evt){    
       if(evt.target.id == "menu_content")
          return;
       //For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
       if($(evt.target).closest('#menu_content').length)
          return;             

      //Do processing of click event here for every element except with id menu_content

});

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

How can I add numbers in a Bash script?

There are a thousand and one ways to do it. Here's one using dc (a reverse-polish desk calculator which supports unlimited precision arithmetic):

dc <<<"$num1 $num2 + p"

But if that's too bash-y for you (or portability matters) you could say

echo $num1 $num2 + p | dc

But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc is here for you:

bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc

That said, there are some unrelated improvements you could be making to your script:

#!/bin/bash

num=0
metab=0

for ((i=1; i<=2; i++)); do
    for j in output-$i-* ; do # 'for' can glob directly, no need to ls
            echo "$j"

             # 'grep' can read files, no need to use 'cat'
            metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
            num=$(( $num + $metab ))
    done
    echo "$num"
done

As described in Bash FAQ 022, Bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc or dc) is required.

In this case the solution would be

num=$(dc <<<"$num $metab + p")

To add accumulate possibly-floating-point numbers into num.

How do I rotate a picture in WinForms

You can easily do it by calling this method :

public static Bitmap RotateImage(Image image, float angle)
{
    if (image == null)
        throw new ArgumentNullException("image");

    PointF offset = new PointF((float)image.Width / 2, (float)image.Height / 2);

    //create a new empty bitmap to hold rotated image
    Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
    rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(rotatedBmp);

    //Put the rotation point in the center of the image
    g.TranslateTransform(offset.X, offset.Y);

    //rotate the image
    g.RotateTransform(angle);

    //move the image back
    g.TranslateTransform(-offset.X, -offset.Y);

    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0, 0));

    return rotatedBmp;
}

don't forget to add a reference to System.Drawing.dll on your project

Example of this method call :

Image image = new Bitmap("waves.png");
Image newImage = RotateImage(image, 360);
newImage.Save("newWaves.png");