Programs & Examples On #S#arp

Execute a shell script in current shell with sudo permission

Even the first answer is absolutely brilliant, you probably want to only run script under sudo.

You have to specify the absolute path like:

sudo /home/user/example.sh
sudo ~/example.sh

(both are working)

THIS WONT WORK!

sudo /bin/sh example.sh
sudo example.sh

It will always return

sudo: bin/sh: command not found
sudo: example.sh: command not found

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

Scripting SQL Server permissions

declare @DBRoleName varchar(40) = 'yourUserName'
SELECT 'GRANT ' + dbprm.permission_name + ' ON ' + OBJECT_SCHEMA_NAME(major_id) + '.' + OBJECT_NAME(major_id) + ' TO ' + dbrol.name + char(13) COLLATE Latin1_General_CI_AS
from sys.database_permissions dbprm
join sys.database_principals dbrol on
dbprm.grantee_principal_id = dbrol.principal_id
where dbrol.name = @DBRoleName

http://www.sqlserver-dba.com/2014/10/how-to-script-database-role-permissions-and-securables.html

I found this to be an excellent solution for generating a script to replicate access between environments

How to check for DLL dependency?

Try Dependencies (Dec 2019) which is a modern rewrite of the famous Dependency Walker (last update in 2006)

Margin between items in recycler view Android

Instead of using XML to add margin between items in RecyclerView, it's better way to use RecyclerView.ItemDecoration that provide by android framework.

So, I create a library to solve this issue.

https://github.com/TheKhaeng/recycler-view-margin-decoration

enter image description here

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

An item with the same key has already been added

I had this issue on the DBContext. Got the error when I tried run an update-database in Package Manager console to add a migration:

public virtual IDbSet Status { get; set; }

The problem was that the type and the name were the same. I changed it to:

public virtual IDbSet Statuses { get; set; }

@RequestParam vs @PathVariable

1) @RequestParam is used to extract query parameters

http://localhost:3000/api/group/test?id=4

@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

while @PathVariable is used to extract data right from the URI:

http://localhost:3000/api/group/test/4

@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

3) @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute, provided the required attribute is false:

@RestController
@RequestMapping("/home")
public class IndexController {

    @RequestMapping(value = "/name")
    String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
        return "Required element of request param";
    }

}

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

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Displaying better error message than "No JSON object could be decoded"

I had a similar problem this was my code:

    json_file=json.dumps(pyJson)
    file = open("list.json",'w')
    file.write(json_file)  

    json_file = open("list.json","r")
    json_decoded = json.load(json_file)
    print json_decoded

the problem was i had forgotten to file.close() I did it and fixed the problem.

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

What are all the common ways to read a file in Ruby?

You can read the file all at once:

content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}

When the file is large, or may be large, it is usually better to process it line-by-line:

File.foreach( 'file.txt' ) do |line|
  puts line
end

Sometimes you want access to the file handle though or control the reads yourself:

File.open( 'file.txt' ) do |f|
  loop do
    break if not line = f.gets
    puts "#{f.lineno}: #{line}"
  end
end

In case of binary files, you may specify a nil-separator and a block size, like so:

File.open('file.bin', 'rb') do |f|
  loop do
    break if not buf = f.gets(nil, 80)
    puts buf.unpack('H*')
  end
end

Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):

begin
  f = File.open 'file.txt'
  while line = f.gets
    puts line
  end
ensure
  f.close
end

References: File API and the IO API.

What is the best way to seed a database in Rails?

Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.

Convert a Python list with strings all to lowercase or uppercase

a student asking, another student with the same problem answering :))

fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon']
newList = []
for fruit in fruits:
    newList.append(fruit.upper())
print(newList)

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

Find mouse position relative to element

I implemented an other solution that I think is very simple so I thought I'd share with you guys.

So, the problem for me was that the dragged div would jump to 0,0 for the mouse cursor. So I needed to capture the mouses position on the div to adjust the divs new position.

I read the divs PageX and PageY and set the top and left of the according to that and then to get the values to adjust the coordinates to keep the cursor in the initial position in the div I use a onDragStart listener and store the e.nativeEvent.layerX and e.nativeEvent.layerY that only in the initial trigger gives you the mouses position within the draggable div.

Example code :

 onDrag={(e) => {
          let newCoords;
          newCoords = { x: e.pageX - this.state.correctionX, y: e.pageY - this.state.correctionY };
          this.props.onDrag(newCoords, e, item.id);
        }}
        onDragStart={
          (e) => {
            this.setState({
              correctionX: e.nativeEvent.layerX,
              correctionY: e.nativeEvent.layerY,
            });
          }

I hope this will help someone that went through the same problems I went through :)

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_

font awesome icon in select option

Full Sample and newer version:https://codepen.io/Nagibaba/pen/bagEgx enter image description here

_x000D_
_x000D_
select {_x000D_
  font-family: 'FontAwesome', 'sans-serif';_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<div>_x000D_
  <select>_x000D_
    <option value="fa-align-left">&#xf036; fa-align-left</option>_x000D_
    <option value="fa-align-right">&#xf038; fa-align-right</option>_x000D_
    <option value="fa-amazon">&#xf270; fa-amazon</option>_x000D_
    <option value="fa-ambulance">&#xf0f9; fa-ambulance</option>_x000D_
    <option value="fa-anchor">&#xf13d; fa-anchor</option>_x000D_
    <option value="fa-android">&#xf17b; fa-android</option>_x000D_
    <option value="fa-angellist">&#xf209; fa-angellist</option>_x000D_
    <option value="fa-angle-double-down">&#xf103; fa-angle-double-down</option>_x000D_
    <option value="fa-angle-double-left">&#xf100; fa-angle-double-left</option>_x000D_
    <option value="fa-angle-double-right">&#xf101; fa-angle-double-right</option>_x000D_
    <option value="fa-angle-double-up">&#xf102; fa-angle-double-up</option>_x000D_
_x000D_
    <option value="fa-angle-left">&#xf104; fa-angle-left</option>_x000D_
    <option value="fa-angle-right">&#xf105; fa-angle-right</option>_x000D_
    <option value="fa-angle-up">&#xf106; fa-angle-up</option>_x000D_
    <option value="fa-apple">&#xf179; fa-apple</option>_x000D_
    <option value="fa-archive">&#xf187; fa-archive</option>_x000D_
    <option value="fa-area-chart">&#xf1fe; fa-area-chart</option>_x000D_
    <option value="fa-arrow-circle-down">&#xf0ab; fa-arrow-circle-down</option>_x000D_
    <option value="fa-arrow-circle-left">&#xf0a8; fa-arrow-circle-left</option>_x000D_
    <option value="fa-arrow-circle-o-down">&#xf01a; fa-arrow-circle-o-down</option>_x000D_
    <option value="fa-arrow-circle-o-left">&#xf190; fa-arrow-circle-o-left</option>_x000D_
    <option value="fa-arrow-circle-o-right">&#xf18e; fa-arrow-circle-o-right</option>_x000D_
    <option value="fa-arrow-circle-o-up">&#xf01b; fa-arrow-circle-o-up</option>_x000D_
    <option value="fa-arrow-circle-right">&#xf0a9; fa-arrow-circle-right</option>_x000D_
    <option value="fa-arrow-circle-up">&#xf0aa; fa-arrow-circle-up</option>_x000D_
    <option value="fa-arrow-down">&#xf063; fa-arrow-down</option>_x000D_
    <option value="fa-arrow-left">&#xf060; fa-arrow-left</option>_x000D_
    <option value="fa-arrow-right">&#xf061; fa-arrow-right</option>_x000D_
    <option value="fa-arrow-up">&#xf062; fa-arrow-up</option>_x000D_
    <option value="fa-arrows">&#xf047; fa-arrows</option>_x000D_
    <option value="fa-arrows-alt">&#xf0b2; fa-arrows-alt</option>_x000D_
    <option value="fa-arrows-h">&#xf07e; fa-arrows-h</option>_x000D_
    <option value="fa-arrows-v">&#xf07d; fa-arrows-v</option>_x000D_
    <option value="fa-asterisk">&#xf069; fa-asterisk</option>_x000D_
    <option value="fa-at">&#xf1fa; fa-at</option>_x000D_
    <option value="fa-automobile">&#xf1b9; fa-automobile</option>_x000D_
    <option value="fa-backward">&#xf04a; fa-backward</option>_x000D_
    <option value="fa-balance-scale">&#xf24e; fa-balance-scale</option>_x000D_
    <option value="fa-ban">&#xf05e; fa-ban</option>_x000D_
    <option value="fa-bank">&#xf19c; fa-bank</option>_x000D_
    <option value="fa-bar-chart">&#xf080; fa-bar-chart</option>_x000D_
    <option value="fa-bar-chart-o">&#xf080; fa-bar-chart-o</option>_x000D_
_x000D_
    <option value="fa-battery-full">&#xf240; fa-battery-full</option>_x000D_
    n value="fa-beer">&#xf0fc; fa-beer</option>_x000D_
    <option value="fa-behance">&#xf1b4; fa-behance</option>_x000D_
    <option value="fa-behance-square">&#xf1b5; fa-behance-square</option>_x000D_
    <option value="fa-bell">&#xf0f3; fa-bell</option>_x000D_
    <option value="fa-bell-o">&#xf0a2; fa-bell-o</option>_x000D_
    <option value="fa-bell-slash">&#xf1f6; fa-bell-slash</option>_x000D_
    <option value="fa-bell-slash-o">&#xf1f7; fa-bell-slash-o</option>_x000D_
    <option value="fa-bicycle">&#xf206; fa-bicycle</option>_x000D_
    <option value="fa-binoculars">&#xf1e5; fa-binoculars</option>_x000D_
    <option value="fa-birthday-cake">&#xf1fd; fa-birthday-cake</option>_x000D_
    <option value="fa-bitbucket">&#xf171; fa-bitbucket</option>_x000D_
    <option value="fa-bitbucket-square">&#xf172; fa-bitbucket-square</option>_x000D_
    <option value="fa-bitcoin">&#xf15a; fa-bitcoin</option>_x000D_
    <option value="fa-black-tie">&#xf27e; fa-black-tie</option>_x000D_
    <option value="fa-bold">&#xf032; fa-bold</option>_x000D_
    <option value="fa-bolt">&#xf0e7; fa-bolt</option>_x000D_
    <option value="fa-bomb">&#xf1e2; fa-bomb</option>_x000D_
    <option value="fa-book">&#xf02d; fa-book</option>_x000D_
    <option value="fa-bookmark">&#xf02e; fa-bookmark</option>_x000D_
    <option value="fa-bookmark-o">&#xf097; fa-bookmark-o</option>_x000D_
    <option value="fa-briefcase">&#xf0b1; fa-briefcase</option>_x000D_
    <option value="fa-btc">&#xf15a; fa-btc</option>_x000D_
    <option value="fa-bug">&#xf188; fa-bug</option>_x000D_
    <option value="fa-building">&#xf1ad; fa-building</option>_x000D_
    <option value="fa-building-o">&#xf0f7; fa-building-o</option>_x000D_
    <option value="fa-bullhorn">&#xf0a1; fa-bullhorn</option>_x000D_
    <option value="fa-bullseye">&#xf140; fa-bullseye</option>_x000D_
    <option value="fa-bus">&#xf207; fa-bus</option>_x000D_
    <option value="fa-cab">&#xf1ba; fa-cab</option>_x000D_
    <option value="fa-calendar">&#xf073; fa-calendar</option>_x000D_
    <option value="fa-camera">&#xf030; fa-camera</option>_x000D_
    <option value="fa-car">&#xf1b9; fa-car</option>_x000D_
    <option value="fa-caret-up">&#xf0d8; fa-caret-up</option>_x000D_
    <option value="fa-cart-plus">&#xf217; fa-cart-plus</option>_x000D_
    <option value="fa-cc">&#xf20a; fa-cc</option>_x000D_
    <option value="fa-cc-amex">&#xf1f3; fa-cc-amex</option>_x000D_
    <option value="fa-cc-jcb">&#xf24b; fa-cc-jcb</option>_x000D_
    <option value="fa-cc-paypal">&#xf1f4; fa-cc-paypal</option>_x000D_
    <option value="fa-cc-stripe">&#xf1f5; fa-cc-stripe</option>_x000D_
    <option value="fa-cc-visa">&#xf1f0; fa-cc-visa</option>_x000D_
    <option value="fa-chain">&#xf0c1; fa-chain</option>_x000D_
    <option value="fa-check">&#xf00c; fa-check</option>_x000D_
    <option value="fa-chevron-left">&#xf053; fa-chevron-left</option>_x000D_
    <option value="fa-chevron-right">&#xf054; fa-chevron-right</option>_x000D_
    <option value="fa-chevron-up">&#xf077; fa-chevron-up</option>_x000D_
    <option value="fa-child">&#xf1ae; fa-child</option>_x000D_
    <option value="fa-chrome">&#xf268; fa-chrome</option>_x000D_
    <option value="fa-circle">&#xf111; fa-circle</option>_x000D_
    <option value="fa-circle-o">&#xf10c; fa-circle-o</option>_x000D_
    <option value="fa-circle-o-notch">&#xf1ce; fa-circle-o-notch</option>_x000D_
    <option value="fa-circle-thin">&#xf1db; fa-circle-thin</option>_x000D_
    <option value="fa-clipboard">&#xf0ea; fa-clipboard</option>_x000D_
    <option value="fa-clock-o">&#xf017; fa-clock-o</option>_x000D_
    <option value="fa-clone">&#xf24d; fa-clone</option>_x000D_
    <option value="fa-close">&#xf00d; fa-close</option>_x000D_
    <option value="fa-cloud">&#xf0c2; fa-cloud</option>_x000D_
    <option value="fa-cloud-download">&#xf0ed; fa-cloud-download</option>_x000D_
    <option value="fa-cloud-upload">&#xf0ee; fa-cloud-upload</option>_x000D_
    <option value="fa-cny">&#xf157; fa-cny</option>_x000D_
    <option value="fa-code">&#xf121; fa-code</option>_x000D_
    <option value="fa-code-fork">&#xf126; fa-code-fork</option>_x000D_
    <option value="fa-codepen">&#xf1cb; fa-codepen</option>_x000D_
    <option value="fa-coffee">&#xf0f4; fa-coffee</option>_x000D_
    <option value="fa-cog">&#xf013; fa-cog</option>_x000D_
    <option value="fa-cogs">&#xf085; fa-cogs</option>_x000D_
    <option value="fa-columns">&#xf0db; fa-columns</option>_x000D_
    <option value="fa-comment">&#xf075; fa-comment</option>_x000D_
    <option value="fa-comment-o">&#xf0e5; fa-comment-o</option>_x000D_
    <option value="fa-commenting">&#xf27a; fa-commenting</option>_x000D_
    <option value="fa-commenting-o">&#xf27b; fa-commenting-o</option>_x000D_
    <option value="fa-comments">&#xf086; fa-comments</option>_x000D_
    <option value="fa-comments-o">&#xf0e6; fa-comments-o</option>_x000D_
    <option value="fa-compass">&#xf14e; fa-compass</option>_x000D_
    <option value="fa-compress">&#xf066; fa-compress</option>_x000D_
    <option value="fa-connectdevelop">&#xf20e; fa-connectdevelop</option>_x000D_
    <option value="fa-contao">&#xf26d; fa-contao</option>_x000D_
    <option value="fa-copy">&#xf0c5; fa-copy</option>_x000D_
    <option value="fa-copyright">&#xf1f9; fa-copyright</option>_x000D_
    <option value="fa-creative-commons">&#xf25e; fa-creative-commons</option>_x000D_
    <option value="fa-credit-card">&#xf09d; fa-credit-card</option>_x000D_
    <option value="fa-crop">&#xf125; fa-crop</option>_x000D_
    <option value="fa-crosshairs">&#xf05b; fa-crosshairs</option>_x000D_
    <option value="fa-css3">&#xf13c; fa-css3</option>_x000D_
    <option value="fa-cube">&#xf1b2; fa-cube</option>_x000D_
    <option value="fa-cubes">&#xf1b3; fa-cubes</option>_x000D_
    <option value="fa-cut">&#xf0c4; fa-cut</option>_x000D_
    <option value="fa-cutlery">&#xf0f5; fa-cutlery</option>_x000D_
    <option value="fa-dashboard">&#xf0e4; fa-dashboard</option>_x000D_
    <option value="fa-dashcube">&#xf210; fa-dashcube</option>_x000D_
    <option value="fa-database">&#xf1c0; fa-database</option>_x000D_
    <option value="fa-dedent">&#xf03b; fa-dedent</option>_x000D_
    <option value="fa-delicious">&#xf1a5; fa-delicious</option>_x000D_
    <option value="fa-desktop">&#xf108; fa-desktop</option>_x000D_
    <option value="fa-deviantart">&#xf1bd; fa-deviantart</option>_x000D_
    <option value="fa-diamond">&#xf219; fa-diamond</option>_x000D_
    <option value="fa-digg">&#xf1a6; fa-digg</option>_x000D_
    <option value="fa-dollar">&#xf155; fa-dollar</option>_x000D_
    <option value="fa-download">&#xf019; fa-download</option>_x000D_
    <option value="fa-dribbble">&#xf17d; fa-dribbble</option>_x000D_
    <option value="fa-dropbox">&#xf16b; fa-dropbox</option>_x000D_
    <option value="fa-drupal">&#xf1a9; fa-drupal</option>_x000D_
    <option value="fa-edit">&#xf044; fa-edit</option>_x000D_
    <option value="fa-eject">&#xf052; fa-eject</option>_x000D_
    <option value="fa-ellipsis-h">&#xf141; fa-ellipsis-h</option>_x000D_
    <option value="fa-ellipsis-v">&#xf142; fa-ellipsis-v</option>_x000D_
    <option value="fa-empire">&#xf1d1; fa-empire</option>_x000D_
    <option value="fa-envelope">&#xf0e0; fa-envelope</option>_x000D_
    <option value="fa-envelope-o">&#xf003; fa-envelope-o</option>_x000D_
    <option value="fa-eur">&#xf153; fa-eur</option>_x000D_
    <option value="fa-euro">&#xf153; fa-euro</option>_x000D_
    <option value="fa-exchange">&#xf0ec; fa-exchange</option>_x000D_
    <option value="fa-exclamation">&#xf12a; fa-exclamation</option>_x000D_
    <option value="fa-exclamation-circle">&#xf06a; fa-exclamation-circle</option>_x000D_
    <option value="fa-exclamation-triangle">&#xf071; fa-exclamation-triangle</option>_x000D_
    <option value="fa-expand">&#xf065; fa-expand</option>_x000D_
    <option value="fa-expeditedssl">&#xf23e; fa-expeditedssl</option>_x000D_
    <option value="fa-external-link">&#xf08e; fa-external-link</option>_x000D_
    <option value="fa-external-link-square">&#xf14c; fa-external-link-square</option>_x000D_
    <option value="fa-eye">&#xf06e; fa-eye</option>_x000D_
    <option value="fa-eye-slash">&#xf070; fa-eye-slash</option>_x000D_
    <option value="fa-eyedropper">&#xf1fb; fa-eyedropper</option>_x000D_
    <option value="fa-facebook">&#xf09a; fa-facebook</option>_x000D_
    <option value="fa-facebook-f">&#xf09a; fa-facebook-f</option>_x000D_
    <option value="fa-facebook-official">&#xf230; fa-facebook-official</option>_x000D_
    <option value="fa-facebook-square">&#xf082; fa-facebook-square</option>_x000D_
    <option value="fa-fast-backward">&#xf049; fa-fast-backward</option>_x000D_
    <option value="fa-fast-forward">&#xf050; fa-fast-forward</option>_x000D_
    <option value="fa-fax">&#xf1ac; fa-fax</option>_x000D_
    <option value="fa-feed">&#xf09e; fa-feed</option>_x000D_
    <option value="fa-female">&#xf182; fa-female</option>_x000D_
    <option value="fa-fighter-jet">&#xf0fb; fa-fighter-jet</option>_x000D_
    <option value="fa-file">&#xf15b; fa-file</option>_x000D_
    <option value="fa-file-archive-o">&#xf1c6; fa-file-archive-o</option>_x000D_
    <option value="fa-file-audio-o">&#xf1c7; fa-file-audio-o</option>_x000D_
    <option value="fa-file-code-o">&#xf1c9; fa-file-code-o</option>_x000D_
    <option value="fa-file-excel-o">&#xf1c3; fa-file-excel-o</option>_x000D_
    <option value="fa-file-image-o">&#xf1c5; fa-file-image-o</option>_x000D_
    <option value="fa-file-movie-o">&#xf1c8; fa-file-movie-o</option>_x000D_
    <option value="fa-file-o">&#xf016; fa-file-o</option>_x000D_
    <option value="fa-file-pdf-o">&#xf1c1; fa-file-pdf-o</option>_x000D_
    <option value="fa-file-photo-o">&#xf1c5; fa-file-photo-o</option>_x000D_
    <option value="fa-file-picture-o">&#xf1c5; fa-file-picture-o</option>_x000D_
    <option value="fa-file-powerpoint-o">&#xf1c4; fa-file-powerpoint-o</option>_x000D_
    <option value="fa-file-sound-o">&#xf1c7; fa-file-sound-o</option>_x000D_
    <option value="fa-file-text">&#xf15c; fa-file-text</option>_x000D_
    <option value="fa-file-text-o">&#xf0f6; fa-file-text-o</option>_x000D_
    <option value="fa-file-video-o">&#xf1c8; fa-file-video-o</option>_x000D_
    <option value="fa-file-word-o">&#xf1c2; fa-file-word-o</option>_x000D_
    <option value="fa-file-zip-o">&#xf1c6; fa-file-zip-o</option>_x000D_
    <option value="fa-files-o">&#xf0c5; fa-files-o</option>_x000D_
    <option value="fa-film">&#xf008; fa-film</option>_x000D_
    <option value="fa-filter">&#xf0b0; fa-filter</option>_x000D_
    <option value="fa-fire">&#xf06d; fa-fire</option>_x000D_
    <option value="fa-fire-extinguisher">&#xf134; fa-fire-extinguisher</option>_x000D_
    <option value="fa-firefox">&#xf269; fa-firefox</option>_x000D_
    <option value="fa-flag">&#xf024; fa-flag</option>_x000D_
    <option value="fa-flag-checkered">&#xf11e; fa-flag-checkered</option>_x000D_
    <option value="fa-flag-o">&#xf11d; fa-flag-o</option>_x000D_
    <option value="fa-flash">&#xf0e7; fa-flash</option>_x000D_
    <option value="fa-flask">&#xf0c3; fa-flask</option>_x000D_
    <option value="fa-flickr">&#xf16e; fa-flickr</option>_x000D_
    <option value="fa-floppy-o">&#xf0c7; fa-floppy-o</option>_x000D_
    <option value="fa-folder">&#xf07b; fa-folder</option>_x000D_
    <option value="fa-folder-o">&#xf114; fa-folder-o</option>_x000D_
    <option value="fa-folder-open">&#xf07c; fa-folder-open</option>_x000D_
    <option value="fa-folder-open-o">&#xf115; fa-folder-open-o</option>_x000D_
    <option value="fa-font">&#xf031; fa-font</option>_x000D_
    <option value="fa-fonticons">&#xf280; fa-fonticons</option>_x000D_
    <option value="fa-forumbee">&#xf211; fa-forumbee</option>_x000D_
    <option value="fa-forward">&#xf04e; fa-forward</option>_x000D_
    <option value="fa-foursquare">&#xf180; fa-foursquare</option>_x000D_
    <option value="fa-frown-o">&#xf119; fa-frown-o</option>_x000D_
    <option value="fa-futbol-o">&#xf1e3; fa-futbol-o</option>_x000D_
    <option value="fa-gamepad">&#xf11b; fa-gamepad</option>_x000D_
    <option value="fa-gavel">&#xf0e3; fa-gavel</option>_x000D_
    <option value="fa-gbp">&#xf154; fa-gbp</option>_x000D_
    <option value="fa-ge">&#xf1d1; fa-ge</option>_x000D_
    <option value="fa-gear">&#xf013; fa-gear</option>_x000D_
    <option value="fa-gears">&#xf085; fa-gears</option>_x000D_
    <option value="fa-genderless">&#xf22d; fa-genderless</option>_x000D_
    <option value="fa-get-pocket">&#xf265; fa-get-pocket</option>_x000D_
    <option value="fa-gg">&#xf260; fa-gg</option>_x000D_
    <option value="fa-gg-circle">&#xf261; fa-gg-circle</option>_x000D_
    <option value="fa-gift">&#xf06b; fa-gift</option>_x000D_
    <option value="fa-git">&#xf1d3; fa-git</option>_x000D_
    <option value="fa-git-square">&#xf1d2; fa-git-square</option>_x000D_
    <option value="fa-github">&#xf09b; fa-github</option>_x000D_
    <option value="fa-github-alt">&#xf113; fa-github-alt</option>_x000D_
    <option value="fa-github-square">&#xf092; fa-github-square</option>_x000D_
    <option value="fa-gittip">&#xf184; fa-gittip</option>_x000D_
    <option value="fa-glass">&#xf000; fa-glass</option>_x000D_
    <option value="fa-globe">&#xf0ac; fa-globe</option>_x000D_
    <option value="fa-google">&#xf1a0; fa-google</option>_x000D_
    <option value="fa-google-plus">&#xf0d5; fa-google-plus</option>_x000D_
    <option value="fa-google-plus-square">&#xf0d4; fa-google-plus-square</option>_x000D_
    <option value="fa-google-wallet">&#xf1ee; fa-google-wallet</option>_x000D_
    <option value="fa-graduation-cap">&#xf19d; fa-graduation-cap</option>_x000D_
    <option value="fa-gratipay">&#xf184; fa-gratipay</option>_x000D_
    <option value="fa-group">&#xf0c0; fa-group</option>_x000D_
    <option value="fa-h-square">&#xf0fd; fa-h-square</option>_x000D_
    <option value="fa-hacker-news">&#xf1d4; fa-hacker-news</option>_x000D_
    <option value="fa-hand-grab-o">&#xf255; fa-hand-grab-o</option>_x000D_
    <option value="fa-hand-lizard-o">&#xf258; fa-hand-lizard-o</option>_x000D_
    <option value="fa-hand-o-down">&#xf0a7; fa-hand-o-down</option>_x000D_
    <option value="fa-hand-o-left">&#xf0a5; fa-hand-o-left</option>_x000D_
    <option value="fa-hand-o-right">&#xf0a4; fa-hand-o-right</option>_x000D_
    <option value="fa-hand-o-up">&#xf0a6; fa-hand-o-up</option>_x000D_
    <option value="fa-hand-paper-o">&#xf256; fa-hand-paper-o</option>_x000D_
    <option value="fa-hand-peace-o">&#xf25b; fa-hand-peace-o</option>_x000D_
    <option value="fa-hand-pointer-o">&#xf25a; fa-hand-pointer-o</option>_x000D_
    <option value="fa-hand-rock-o">&#xf255; fa-hand-rock-o</option>_x000D_
    <option value="fa-hand-scissors-o">&#xf257; fa-hand-scissors-o</option>_x000D_
    <option value="fa-hand-spock-o">&#xf259; fa-hand-spock-o</option>_x000D_
    <option value="fa-hand-stop-o">&#xf256; fa-hand-stop-o</option>_x000D_
    <option value="fa-hdd-o">&#xf0a0; fa-hdd-o</option>_x000D_
    <option value="fa-header">&#xf1dc; fa-header</option>_x000D_
    <option value="fa-headphones">&#xf025; fa-headphones</option>_x000D_
    <option value="fa-heart">&#xf004; fa-heart</option>_x000D_
    <option value="fa-heart-o">&#xf08a; fa-heart-o</option>_x000D_
    <option value="fa-heartbeat">&#xf21e; fa-heartbeat</option>_x000D_
    <option value="fa-history">&#xf1da; fa-history</option>_x000D_
    <option value="fa-home">&#xf015; fa-home</option>_x000D_
    <option value="fa-hospital-o">&#xf0f8; fa-hospital-o</option>_x000D_
    <option value="fa-hotel">&#xf236; fa-hotel</option>_x000D_
    <option value="fa-hourglass">&#xf254; fa-hourglass</option>_x000D_
    <option value="fa-hourglass-1">&#xf251; fa-hourglass-1</option>_x000D_
    <option value="fa-hourglass-2">&#xf252; fa-hourglass-2</option>_x000D_
    <option value="fa-hourglass-3">&#xf253; fa-hourglass-3</option>_x000D_
    <option value="fa-hourglass-end">&#xf253; fa-hourglass-end</option>_x000D_
    <option value="fa-hourglass-half">&#xf252; fa-hourglass-half</option>_x000D_
    <option value="fa-hourglass-o">&#xf250; fa-hourglass-o</option>_x000D_
    <option value="fa-hourglass-start">&#xf251; fa-hourglass-start</option>_x000D_
    <option value="fa-houzz">&#xf27c; fa-houzz</option>_x000D_
    <option value="fa-html5">&#xf13b; fa-html5</option>_x000D_
    <option value="fa-i-cursor">&#xf246; fa-i-cursor</option>_x000D_
    <option value="fa-ils">&#xf20b; fa-ils</option>_x000D_
    <option value="fa-image">&#xf03e; fa-image</option>_x000D_
    <option value="fa-inbox">&#xf01c; fa-inbox</option>_x000D_
    <option value="fa-indent">&#xf03c; fa-indent</option>_x000D_
    <option value="fa-industry">&#xf275; fa-industry</option>_x000D_
    <option value="fa-info">&#xf129; fa-info</option>_x000D_
    <option value="fa-info-circle">&#xf05a; fa-info-circle</option>_x000D_
    <option value="fa-inr">&#xf156; fa-inr</option>_x000D_
    <option value="fa-instagram">&#xf16d; fa-instagram</option>_x000D_
    <option value="fa-institution">&#xf19c; fa-institution</option>_x000D_
    <option value="fa-internet-explorer">&#xf26b; fa-internet-explorer</option>_x000D_
    <option value="fa-intersex">&#xf224; fa-intersex</option>_x000D_
    <option value="fa-ioxhost">&#xf208; fa-ioxhost</option>_x000D_
    <option value="fa-italic">&#xf033; fa-italic</option>_x000D_
    <option value="fa-joomla">&#xf1aa; fa-joomla</option>_x000D_
    <option value="fa-jpy">&#xf157; fa-jpy</option>_x000D_
    <option value="fa-jsfiddle">&#xf1cc; fa-jsfiddle</option>_x000D_
    <option value="fa-key">&#xf084; fa-key</option>_x000D_
    <option value="fa-keyboard-o">&#xf11c; fa-keyboard-o</option>_x000D_
    <option value="fa-krw">&#xf159; fa-krw</option>_x000D_
    <option value="fa-language">&#xf1ab; fa-language</option>_x000D_
    <option value="fa-laptop">&#xf109; fa-laptop</option>_x000D_
    <option value="fa-lastfm">&#xf202; fa-lastfm</option>_x000D_
    <option value="fa-lastfm-square">&#xf203; fa-lastfm-square</option>_x000D_
    <option value="fa-leaf">&#xf06c; fa-leaf</option>_x000D_
    <option value="fa-leanpub">&#xf212; fa-leanpub</option>_x000D_
    <option value="fa-legal">&#xf0e3; fa-legal</option>_x000D_
    <option value="fa-lemon-o">&#xf094; fa-lemon-o</option>_x000D_
    <option value="fa-level-down">&#xf149; fa-level-down</option>_x000D_
    <option value="fa-level-up">&#xf148; fa-level-up</option>_x000D_
    <option value="fa-life-bouy">&#xf1cd; fa-life-bouy</option>_x000D_
    <option value="fa-life-buoy">&#xf1cd; fa-life-buoy</option>_x000D_
    <option value="fa-life-ring">&#xf1cd; fa-life-ring</option>_x000D_
    <option value="fa-life-saver">&#xf1cd; fa-life-saver</option>_x000D_
    <option value="fa-lightbulb-o">&#xf0eb; fa-lightbulb-o</option>_x000D_
    <option value="fa-line-chart">&#xf201; fa-line-chart</option>_x000D_
    <option value="fa-link">&#xf0c1; fa-link</option>_x000D_
    <option value="fa-linkedin">&#xf0e1; fa-linkedin</option>_x000D_
    <option value="fa-linkedin-square">&#xf08c; fa-linkedin-square</option>_x000D_
    <option value="fa-linux">&#xf17c; fa-linux</option>_x000D_
    <option value="fa-list">&#xf03a; fa-list</option>_x000D_
    <option value="fa-list-alt">&#xf022; fa-list-alt</option>_x000D_
    <option value="fa-list-ol">&#xf0cb; fa-list-ol</option>_x000D_
    <option value="fa-list-ul">&#xf0ca; fa-list-ul</option>_x000D_
    <option value="fa-location-arrow">&#xf124; fa-location-arrow</option>_x000D_
    <option value="fa-lock">&#xf023; fa-lock</option>_x000D_
    <option value="fa-long-arrow-down">&#xf175; fa-long-arrow-down</option>_x000D_
    <option value="fa-long-arrow-left">&#xf177; fa-long-arrow-left</option>_x000D_
    <option value="fa-long-arrow-right">&#xf178; fa-long-arrow-right</option>_x000D_
    <option value="fa-long-arrow-up">&#xf176; fa-long-arrow-up</option>_x000D_
    <option value="fa-magic">&#xf0d0; fa-magic</option>_x000D_
    <option value="fa-magnet">&#xf076; fa-magnet</option>_x000D_
_x000D_
    <option value="fa-mars-stroke-v">&#xf22a; fa-mars-stroke-v</option>_x000D_
    <option value="fa-maxcdn">&#xf136; fa-maxcdn</option>_x000D_
    <option value="fa-meanpath">&#xf20c; fa-meanpath</option>_x000D_
    <option value="fa-medium">&#xf23a; fa-medium</option>_x000D_
    <option value="fa-medkit">&#xf0fa; fa-medkit</option>_x000D_
    <option value="fa-meh-o">&#xf11a; fa-meh-o</option>_x000D_
    <option value="fa-mercury">&#xf223; fa-mercury</option>_x000D_
    <option value="fa-microphone">&#xf130; fa-microphone</option>_x000D_
    <option value="fa-mobile">&#xf10b; fa-mobile</option>_x000D_
    <option value="fa-motorcycle">&#xf21c; fa-motorcycle</option>_x000D_
    <option value="fa-mouse-pointer">&#xf245; fa-mouse-pointer</option>_x000D_
    <option value="fa-music">&#xf001; fa-music</option>_x000D_
    <option value="fa-navicon">&#xf0c9; fa-navicon</option>_x000D_
    <option value="fa-neuter">&#xf22c; fa-neuter</option>_x000D_
    <option value="fa-newspaper-o">&#xf1ea; fa-newspaper-o</option>_x000D_
    <option value="fa-opencart">&#xf23d; fa-opencart</option>_x000D_
    <option value="fa-openid">&#xf19b; fa-openid</option>_x000D_
    <option value="fa-opera">&#xf26a; fa-opera</option>_x000D_
    <option value="fa-outdent">&#xf03b; fa-outdent</option>_x000D_
    <option value="fa-pagelines">&#xf18c; fa-pagelines</option>_x000D_
    <option value="fa-paper-plane-o">&#xf1d9; fa-paper-plane-o</option>_x000D_
    <option value="fa-paperclip">&#xf0c6; fa-paperclip</option>_x000D_
    <option value="fa-paragraph">&#xf1dd; fa-paragraph</option>_x000D_
    <option value="fa-paste">&#xf0ea; fa-paste</option>_x000D_
    <option value="fa-pause">&#xf04c; fa-pause</option>_x000D_
    <option value="fa-paw">&#xf1b0; fa-paw</option>_x000D_
    <option value="fa-paypal">&#xf1ed; fa-paypal</option>_x000D_
    <option value="fa-pencil">&#xf040; fa-pencil</option>_x000D_
    <option value="fa-pencil-square-o">&#xf044; fa-pencil-square-o</option>_x000D_
    <option value="fa-phone">&#xf095; fa-phone</option>_x000D_
    <option value="fa-photo">&#xf03e; fa-photo</option>_x000D_
    <option value="fa-picture-o">&#xf03e; fa-picture-o</option>_x000D_
    <option value="fa-pie-chart">&#xf200; fa-pie-chart</option>_x000D_
    <option value="fa-pied-piper">&#xf1a7; fa-pied-piper</option>_x000D_
    <option value="fa-pied-piper-alt">&#xf1a8; fa-pied-piper-alt</option>_x000D_
    <option value="fa-pinterest">&#xf0d2; fa-pinterest</option>_x000D_
    <option value="fa-pinterest-p">&#xf231; fa-pinterest-p</option>_x000D_
    <option value="fa-pinterest-square">&#xf0d3; fa-pinterest-square</option>_x000D_
    <option value="fa-plane">&#xf072; fa-plane</option>_x000D_
    <option value="fa-play">&#xf04b; fa-play</option>_x000D_
    <option value="fa-play-c
                  

Array to Collection: Optimized code

Arrays.asList(array)

Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

How to check not in array element

$id = $access_data['Privilege']['id']; 

if(!in_array($id,$user_access_arr));
    $user_access_arr[] = $id;
    $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
    return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));

How to convert unix timestamp to calendar date moment.js

Might be a little late but for new issues like this I use this code:

moment(timestamp, 'X').format('lll');

You can change the format to match your needs and also add timezone like this:

moment(timestamp, 'X').tz(timezone).format('lll');

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

Remove a folder from git tracking

From the git documentation:

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:

$ git rm --cached readme.txt

So maybe don't include the "-r"?

How to access random item in list?

You can do:

list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()

Disabling radio buttons with jQuery

First, the valid syntax is

jQuery("input[name=ticketID]")

second, have you tried:

jQuery(":radio")

instead?

third, why not assign a class to all the radio buttons, and select them by class?

Rails: How to reference images in CSS within Rails 4

Only this snippet does not work for me:

background-image: url(image_path('transparent_2x2.png'));

But rename stylename.scss to stylename.css.scss helps me.

Java; String replace (using regular expressions)?

Try this:

String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");

Be sure to import java.util.regex.

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Another awk variant:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

How to retrieve checkboxes values in jQuery

I have had a similar problem and this is how i solved it using the examples above:

 $(".ms-drop").click(function () {
        $(function showSelectedValues() {
            alert($(".ms-drop input[type=checkbox]:checked").map(
               function () { return this.value; }).get().join(","));
        });
    });

Bootstrap modal opening on page load

I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.

With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.

<script type="text/javascript">
$('#memberModal').modal('show');
</script>

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

python .replace() regex

For this particular case, if using re module is overkill, how about using split (or rsplit) method as

se='</html>'
z.write(article.split(se)[0]+se)

For example,

#!/usr/bin/python

article='''<html>Larala
Ponta Monta 
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')

se='</html>'
z.write(article.split(se)[0]+se)

outputs out.txt as

<html>Larala
Ponta Monta 
</html>

MySQL timezone change?

If you have the SUPER privilege, you can set the global server time zone value at runtime with this statement:

mysql> SET GLOBAL time_zone = timezone;

Where does the .gitignore file belong?

Also, if you create a new account on Github you will have the option to add .gitignore and it will be setup automatically on the right/standard location of your working place. You don't have to add anything in there at the begin, just alter the contents any time you want.

Why is the default value of the string type null instead of an empty string?

The fundamental reason/problem is that the designers of the CLS specification (which defines how languages interact with .net) did not define a means by which class members could specify that they must be called directly, rather than via callvirt, without the caller performing a null-reference check; nor did it provide a meany of defining structures which would not be subject to "normal" boxing.

Had the CLS specification defined such a means, then it would be possible for .net to consistently follow the lead established by the Common Object Model (COM), under which a null string reference was considered semantically equivalent to an empty string, and for other user-defined immutable class types which are supposed to have value semantics to likewise define default values. Essentially, what would happen would be for each member of String, e.g. Length to be written as something like [InvokableOnNull()] int String Length { get { if (this==null) return 0; else return _Length;} }. This approach would have offered very nice semantics for things which should behave like values, but because of implementation issues need to be stored on the heap. The biggest difficulty with this approach is that the semantics of conversion between such types and Object could get a little murky.

An alternative approach would have been to allow the definition of special structure types which did not inherit from Object but instead had custom boxing and unboxing operations (which would convert to/from some other class type). Under such an approach, there would be a class type NullableString which behaves as string does now, and a custom-boxed struct type String, which would hold a single private field Value of type String. Attempting to convert a String to NullableString or Object would return Value if non-null, or String.Empty if null. Attempting to cast to String, a non-null reference to a NullableString instance would store the reference in Value (perhaps storing null if the length was zero); casting any other reference would throw an exception.

Even though strings have to be stored on the heap, there is conceptually no reason why they shouldn't behave like value types that have a non-null default value. Having them be stored as a "normal" structure which held a reference would have been efficient for code that used them as type "string", but would have added an extra layer of indirection and inefficiency when casting to "object". While I don't foresee .net adding either of the above features at this late date, perhaps designers of future frameworks might consider including them.

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

Can enums be subclassed to add new elements?

Under the covers your ENUM is just a regular class generated by the compiler. That generated class extends java.lang.Enum. The technical reason you can't extend the generated class is that the generated class is final. The conceptual reasons for it being final are discussed in this topic. But I'll add the mechanics to the discussion.

Here is a test enum:

public enum TEST {  
    ONE, TWO, THREE;
}

The resulting code from javap:

public final class TEST extends java.lang.Enum<TEST> {
  public static final TEST ONE;
  public static final TEST TWO;
  public static final TEST THREE;
  static {};
  public static TEST[] values();
  public static TEST valueOf(java.lang.String);
}

Conceivably you could type this class on your own and drop the "final". But the compiler prevents you from extending "java.lang.Enum" directly. You could decide NOT to extend java.lang.Enum, but then your class and its derived classes would not be an instanceof java.lang.Enum ... which might not really matter to you any way!

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Disable spell-checking on HTML textfields

If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:

When setting elem.contentEditable you can use either the boolean false or the string "false". But when you set elem.spellcheck, you can only use the boolean - for some reason. Your options are thus:

elem.spellcheck = false;

Or the option Mac provided in his answer:

elem.setAttribute("spellcheck", "false"); // Both string and boolean work here. 

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

already had this type of problem.

my solution was:

delete the folder from svn but keep a copy of the folder somewhere, commit the changes. in the backup-copy, delete recursively all the .svn-folders in it. for this you might run

#!/bin/bash

find -name '.svn' | while read directory;
do
    echo $directory;
    rm -rf "$directory";
done;

delete the local repository and re-check out entire project. don't know whether partial deletion/checkout are sufficient.

regards

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to fix request failed on channel 0

just found out, what was the problem in my case (provider strato): I had the same problem with output "shell request failed on channel 0" in the end.

I have to use the master password with the web-domain name as login. (In German www.wunschname.de, where wunschname is your web-address.)

A ssh login with sftp-user names and the corresponding passwords is without success. (Although scp and sftp works with these sftp users!)

Directory-tree listing in Python

Try this:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)

Update UI from Thread in Android

As recommended by official documentation, you can use AsyncTask to handle work items shorter than 5ms in duration. If your task take more time, lookout for other alternatives.

HandlerThread is one alternative to Thread or AsyncTask. If you need to update UI from HandlerThread, post a message on UI Thread Looper and UI Thread Handler can handle UI updates.

Example code:

Android: Toast in a thread

How do you get the file size in C#?

FileInfo.Length will do the trick (per MSDN it "[g]ets the size, in bytes, of the current file.") There is a nice page on MSDN on common I/O tasks.

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

Javascript Date: next month

If you use moment.js, they have an add function. Here's the link - https://momentjs.com/docs/#/manipulating/add/

moment().add(7, 'months');

I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.

function addMonths(after = 1, now = new Date()) {
        var current;
        if (now.getMonth() == 11) {
            current = new Date(now.getFullYear() + 1, 0, 1);
        } else {
            current = new Date(now.getFullYear(), now.getMonth() + 1, 1);            
        }
        return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
    }

Example

console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))

Output -

Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Replace whitespaces with tabs in linux

Using sed:

T=$(printf "\t")
sed "s/[[:blank:]]\+/$T/g"

or

sed "s/[[:space:]]\+/$T/g"

Change directory in Node.js command prompt

.help will show you all the options. Do .exit in this case

Set the value of an input field

I use 'setAttribute' function:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

How to make a cross-module variable?

I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.

def builtin_find(f, x, d=None):
    for i in x:
        if f(i):
            return i
    return d

import __builtin__
__builtin__.find = builtin_find

Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.

find(lambda i: i < 0, [1, 3, 0, -5, -10])  # Yields -5, the first negative.

Note: You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.

How to both read and write a file in C#

you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder

P.S dont forget to add Console.Readline() after this code snippet else console will not appear.

TextWriter tw = new StreamWriter("filename.txt");
        String text = "Hello";
        tw.WriteLine(text);
        tw.Close();

        TextReader tr = new StreamReader("filename.txt");
        Console.WriteLine(tr.ReadLine());
        tr.Close();

Calling javascript function in iframe

If you can not use it directly and if you encounter this error: Blocked a frame with origin "http://www..com" from accessing a cross-origin frame. You can use postMessage() instead of using the function directly.

TypeScript sorting an array

let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

jQuery creating objects

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

ERROR 1067 (42000): Invalid default value for 'created_at'

Simply, before you run any statements put this in the first line:

SET sql_mode = '';

PLEASE NOTE: this statement should be used only in development, not in production.

How to find the most recent file in a directory using .NET, and without looping?

If you want to search recursively, you can use this beautiful piece of code:

public static FileInfo GetNewestFile(DirectoryInfo directory) {
   return directory.GetFiles()
       .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
       .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
       .FirstOrDefault();                        
}

Just call it the following way:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));

and that's it. Returns a FileInfo instance or null if the directory is empty.

React.js: Identifying different inputs with one onChange handler

I will provide really simple solution to the problem. Suppose we have two inputs username and password,but we want our handle to be easy and generic ,so we can reuse it and don't write boilerplate code.

I.Our form:

                <form>
                    <input type="text" name = "username" onChange={this.onChange} value={this.state.username}/>
                    <input type="text" name = "password" onChange={this.onChange} value={this.state.password}/>
                    <br></br>
                    <button type="submit">Submit</button>
                </form>

II.Our constructor ,which we want to save our username and password ,so we can access them easily:

constructor(props) {
    super(props);
    this.state = {
        username: '',
        password: ''
    };

    this.onSubmit = this.onSubmit.bind(this);
    this.onChange = this.onChange.bind(this);
}

III.The interesting and "generic" handle with only one onChange event is based on this:

onChange(event) {
    let inputName = event.target.name;
    let value = event.target.value;

    this.setState({[inputName]:value});


    event.preventDefault();
}

Let me explain:

1.When a change is detected the onChange(event) is called

2.Then we get the name parameter of the field and its value:

let inputName = event.target.name; ex: username

let value = event.target.value; ex: itsgosho

3.Based on the name parameter we get our value from the state in the constructor and update it with the value:

this.state['username'] = 'itsgosho'

4.The key to note here is that the name of the field must match with our parameter in the state

Hope I helped someone somehow :)

Changing default startup directory for command prompt in Windows 7

Easiest way to do this

  1. Click "Start" and type "cmd" or "command prompt".
  2. Select Top most search application named exactly same "cmd" or "command prompt".
  3. Right Click on it and select "Send To"=>"Desktop".
  4. On Your Desktop New "cmd" Shortcut will appear
  5. Right Click on that icon and choose "properties"
  6. Popup will appear, In "Shortcut" Tab Type the new location in "Start In" option (e.g D:\xyz)
  7. Drag that icon and add/pin it in "Task Bar"

How do I copy an object in Java?

Here's a decent explanation of clone() if you end up needing it...

Here: clone (Java method)

Testing if a site is vulnerable to Sql Injection

The test has to be done on a page that queries a database so yes typically that is a login page because it's the page that can do the most harm but could be an unsecure page as well.

Generally you would have your database queries behind a secure login but if you just have a listing of items or something that you don't care if the world sees a hacker could append some sql injection to the end of the querystring.

The key with SQL Injection is the person doing the injection would have to know that your querying a database so if your not querying a database then no sql inject can be done. If your form is submitting to a database then yes they could SQL Inject that. It's always good practice to use either stored procedures to select/insert/update/delete or make sure you prepare or escape out all the statements that will be hitting the database.

bower command not found

Just like in this question (npm global path prefix) all you need is to set proper npm prefix.

UNIX:

$ npm config set prefix /usr/local
$ npm install -g bower

$ which bower
>> /usr/local/bin/bower

Windows ans NVM:

$ npm config set prefix /c/Users/xxxxxxx/AppData/Roaming/nvm/v8.9.2
$ npm install -g bower

Then bower should be located just in your $PATH.

How can JavaScript save to a local file?

It is not possible to save file locally without involving the local client (browser machine) as I could be a great threat to client machine. You can use link to download that file. If you want to store something like Json data on local machine you can use LocalStorage provided by the browsers, Web Storage

Get all attributes of an element using jQuery

Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.

Vanilla JS:

function getAttributes ( node ) {
    var i,
        attributeNodes = node.attributes,
        length = attributeNodes.length,
        attrs = {};

    for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
    return attrs;
}

Vanilla JS with Array.reduce

Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.

function getAttributes ( node ) {
    var attributeNodeArray = Array.prototype.slice.call( node.attributes );

    return attributeNodeArray.reduce( function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

jQuery

This function expects a jQuery object, not a DOM element.

function getAttributes ( $node ) {
    var attrs = {};
    $.each( $node[0].attributes, function ( index, attribute ) {
        attrs[attribute.name] = attribute.value;
    } );

    return attrs;
}

Underscore

Also works for lodash.

function getAttributes ( node ) {
    return _.reduce( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

lodash

Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.

function getAttributes ( node ) {
    return _.transform( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
    }, {} );
}

Test page

At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").

How to use HTML to print header and footer on every printed page of a document?

Is this something you want to print-only? You could add it to every page on your site and use CSS to define the tag as a print-only media.

As an example, this could be an example header:

<span class="printspan">UNCLASSIFIED</span>

And in your CSS, do something like this:

<style type="text/css" media="screen">
    .printspan
    {
        display: none;
    }
</style>
<style type="text/css" media="print">
    .printspan
    {
        display: inline;
        font-family: Arial, sans-serif;
        font-size: 16 pt;
        color: red;
    }
</style>

Finally, to include the header/footer on every page you might use server-side includes or if you have any pages being generated with PHP or ASP you could simply code it in to a common file.

Edit:

This answer is intended to provide a way to show something on the physical printed version of a document while not showing it otherwise. However just as comments suggest, it doesn't solve the issue of having a footer on multiple printed pages when content overflows.

I'm leaving it here in case it's helpful nevertheless.

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

Fatal error: Call to a member function bind_param() on boolean

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

Process to convert simple Python script into Windows executable

Using py2exe, include this in your setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1}},
    windows = [{'script': "YourScript.py"}],
    zipfile = None,
)

then you can run it through command prompt / Idle, both works for me. Hope it helps

Reading column names alone in a csv file

How about

with open(csv_input_path + file, 'r') as ft:
    header = ft.readline() # read only first line; returns string
    header_list = header.split(',') # returns list

I am assuming your input file is CSV format. If using pandas, it takes more time if the file is big size because it loads the entire data as the dataset.

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

How to view unallocated free space on a hard disk through terminal

To see in TB:

# parted /dev/sda unit TB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in GB:

# parted /dev/sda unit GB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in MB:

# parted /dev/sda unit MB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in bytes:

# parted /dev/sda unit B print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in %:

# parted /dev/sda unit '%' print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in sectors:

# parted /dev/sda unit s print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

Change /dev/sda to whatever device you are trying to find the information about. If you are using the result in any calculations, make sure to trim the trailing characters.

How to quickly test some javascript code?

Following is a free list of tools you can use to check, test and verify your JS code:

  1. Google Code Playground
  2. JavaScript Sandbox
  3. jsbin
  4. jsfiddle
  5. pastebin
  6. jsdo.it
  7. firebug
  8. html5snippet.net

Hope this helps.

Advantages of using display:inline-block vs float:left in CSS

There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.

http://www.brunildo.org/test/inline-block.html

Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.

Easiest way to change font and font size

Use the Font Class to set the control's font and styles.

Try Font Constructor (String, Single)

Label lab  = new Label();
lab.Text ="Font Bold at 24";
lab.Font = new Font("Arial", 20);

or

lab.Font = new Font(FontFamily.GenericSansSerif,
            12.0F, FontStyle.Bold);

To get installed fonts refer this - .NET System.Drawing.Font - Get Available Sizes and Styles

File to byte[] in Java

Simple way to do it:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

python JSON only get keys in first level

for key in data.keys():
    print key

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is defined as such in a declaration block:

DECLARE 
CURSOR cur IS 
  SELECT columns FROM table WHERE condition;
BEGIN
...

an implicit cursor is implented directly in a code block:

...
BEGIN
   SELECT columns INTO variables FROM table where condition;
END;
...

In Bash, how do I add a string after each line in a file?

I prefer echo. using pure bash:

cat file | while read line; do echo ${line}$string; done

Html.Raw() in ASP.NET MVC Razor view

The accepted answer is correct, but I prefer:

@{int count = 0;} 
@foreach (var item in Model.Resources) 
{ 
    @Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")  
    // some code 
    @Html.Raw(count <= 3 ? "</div>" : "")  
    @(count++)
} 

I hope this inspires someone, even though I'm late to the party.

How to clear memory to prevent "out of memory error" in excel vba?

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.

However this won't help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

Simple Pivot Table to Count Unique Values

You can make an additional column to store the uniqueness, then sum that up in your pivot table.

What I mean is, cell C1 should always be 1. Cell C2 should contain the formula =IF(COUNTIF($A$1:$A1,$A2)*COUNTIF($B$1:$B1,$B2)>0,0,1). Copy this formula down so cell C3 would contain =IF(COUNTIF($A$1:$A2,$A3)*COUNTIF($B$1:$B2,$B3)>0,0,1) and so on.

If you have a header cell, you'll want to move these all down a row and your C3 formula should be =IF(COUNTIF($A$2:$A2,$A3)*COUNTIF($B$2:$B2,$B3)>0,0,1).

Forms authentication timeout vs sessionState timeout

The difference is that one (forms time-out) has to do authenticating the user and the other( session timeout) has to do with how long cached data is stored on the server. So they are very independent things so one doesn't take precedence over the other.

Git error: "Please make sure you have the correct access rights and the repository exists"

The rsa.pub (i.e. public key generated), needs to be added on the github>> settings>>ssh keys page. Check that, you have not added this public key in the repository-settings >> deployment keys. If so, remove the entry from here and add to the first place mentioned.

Setup of the pub-private keys in detail.

It will work hence!

What's the difference between returning value or Promise.resolve from then()

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

Quoting from the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

The key thing to notice here is this line:

if x is a promise, adopt its state [3.4]

link: https://promisesaplus.com/#point-49

One-line list comprehension: if-else variants

You can do that with list comprehension too:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A

Why doesn't importing java.util.* include Arrays and Lists?

The difference between

import java.util.*;

and

import java.util.*;
import java.util.List;
import java.util.Arrays;

becomes apparent when the code refers to some other List or Arrays (for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays will be used.

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

Check if an array contains duplicate values

An easy solution, if you've got ES6, uses Set:

_x000D_
_x000D_
function checkIfArrayIsUnique(myArray) {_x000D_
  return myArray.length === new Set(myArray).size;_x000D_
}_x000D_
_x000D_
let uniqueArray = [1, 2, 3, 4, 5];_x000D_
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);_x000D_
_x000D_
let nonUniqueArray = [1, 1, 2, 3, 4, 5];_x000D_
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
_x000D_
_x000D_
_x000D_

Check if inputs are empty using jQuery

The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

File Upload In Angular?

I have used the following tool from priming with success. I have no skin in the game with primeNg, just passing on my suggestion.

http://www.primefaces.org/primeng/#/fileupload

how to destroy an object in java?

Set to null. Then there are no references anymore and the object will become eligible for Garbage Collection. GC will automatically remove the object from the heap.

How to call a JavaScript function from PHP?

I don't accept the naysayers' answers.

If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.

onClick is a kludge that involves the end-user, hence not acceptable.

@umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):

<script type="text/javascript">
function JSFunction() {
    alert('In test Function');   // This demonstrates that the function was called
}
</script>

<?php
// Call a JS function "from" php

if (true) {   // This if() is to point out that you might
              // want to call JSFunction conditionally
    // An echo like this is how you implant the 'call' in a way
    // that it will be invoked in the client.
    echo '<script type="text/javascript">
         JSFunction();
    </script>';
}

Increasing the maximum post size

I had been facing similar problem in downloading big files this works fine for me now:

safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On

Hope this helps.

Bootstrap 3: how to make head of dropdown link clickable in navbar

This enables the link in the top-level menu of the dropdown when it's opened and disables it when closed, with the only drawback of apparently having to "tap" twice outside of the dropdown to close it in mobile devices.

$(document).on("page:load", function(){
    $('body').on('show.bs.dropdown', function (e) {
        $(e.relatedTarget).addClass('disabled')
    });
    $('body').on('hide.bs.dropdown', function (e) {
        $(e.relatedTarget).removeClass('disabled')
    });
});

Note this assumes the "standard" markup and Turbolinks (Rails). You can try with $(document).ready(...)

How can I consume a WSDL (SOAP) web service in Python?

There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: python zeep.

See also this answer for an example.

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

jQuery set checkbox checked

This works.

 $("div.row-form input[type='checkbox']").attr('checked','checked');

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

How to post SOAP Request from PHP

You might want to look here and here.

A Little code example from the first link:

<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
        print "Error: ". $fault;
        }
else if ($price == -1) {
        print "The book is not in the database.";
} else {
        // otherwise output the result
        print "The price of book number ". $param[isbn] ." is $". $price;
        }
// kill object
unset($client);
?>

Android RelativeLayout programmatically Set "centerInParent"

Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:

    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

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

I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).

My implementation follows (It's written in Python; I have not tested it):

# degrees to radians
def deg2rad(degrees):
    return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
    return 180.0*radians/math.pi

# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0  # Major semiaxis [m]
WGS84_b = 6356752.3  # Minor semiaxis [m]

# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
    # http://en.wikipedia.org/wiki/Earth_radius
    An = WGS84_a*WGS84_a * math.cos(lat)
    Bn = WGS84_b*WGS84_b * math.sin(lat)
    Ad = WGS84_a * math.cos(lat)
    Bd = WGS84_b * math.sin(lat)
    return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )

# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
    lat = deg2rad(latitudeInDegrees)
    lon = deg2rad(longitudeInDegrees)
    halfSide = 1000*halfSideInKm

    # Radius of Earth at given latitude
    radius = WGS84EarthRadius(lat)
    # Radius of the parallel at given latitude
    pradius = radius*math.cos(lat)

    latMin = lat - halfSide/radius
    latMax = lat + halfSide/radius
    lonMin = lon - halfSide/pradius
    lonMax = lon + halfSide/pradius

    return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))

EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):

def dps2deg(degrees, primes, seconds):
    return degrees + primes/60.0 + seconds/3600.0

def deg2dps(degrees):
    intdeg = math.floor(degrees)
    primes = (degrees - intdeg)*60.0
    intpri = math.floor(primes)
    seconds = (primes - intpri)*60.0
    intsec = round(seconds)
    return (int(intdeg), int(intpri), int(intsec))

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Add this config to your webpack config file when using webpack-dev-server (you can still specify the host as 0.0.0.0).

devServer: {
    disableHostCheck: true,
    host: '0.0.0.0',
    port: 3000
}

Add params to given URL in Python

You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded).

Check out urllib.urlencode:

>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'

In python3:

from urllib import parse
parse.urlencode({'lang':'en','tag':'python'})

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Replacing instances of a character in a string

You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:

name = "India"
result=name .replace("d",'*')

Output: In*ia

Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le

Code:

name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

Axios handling errors

You can go like this: error.response.data
In my case, I got error property from backend. So, I used error.response.data.error

My code:

axios
  .get(`${API_BASE_URL}/students`)
  .then(response => {
     return response.data
  })
  .then(data => {
     console.log(data)
  })
  .catch(error => {
     console.log(error.response.data.error)
  })

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

also can try these steps

In the SQL Server, 1.Open one data base 2.Clic in the option 'Server Obtect' 3.Clic in 'Linked Servers' 4.Clic in 'Providers' 5.Clic Rigth in 'Microsoft.ACE.OLEDB.12.0' 6.Uncheck all the options and close

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

What's the bad magic number error?

So i had the same error :importError bad magic number. This was on windows 10

This error was because i installed mysql-connector

So i had to; pip uninstall mysql-comnector pip uninstall mysql-connector-python

pip install mysql-connector-python

Can't use System.Windows.Forms

Adding System.Windows.Forms reference requires .NET Framework project type:

I was using .NET Core project type. This project type doesn't allow us to add assemblies into its project references. I had to move to .NET Framework project type before adding System.Windows.Forms assembly to my references as described in Kendall Frey answer.

Note: There is reference System_Windows_Forms available under COM tab (for both .NET Core and .NET Framework). It is not the right one. It has to be System.Windows.Forms under Assemblies tab.

Set the location in iPhone Simulator

Pre iOS 5 you could do it in code:

I use this snippet just before the @implementation of the class where I need my fake heading and location data.

#if (TARGET_IPHONE_SIMULATOR)
@interface MyHeading : CLHeading
    -(CLLocationDirection) magneticHeading;
    -(CLLocationDirection) trueHeading;
@end

@implementation MyHeading
    -(CLLocationDirection) magneticHeading { return 90; }
    -(CLLocationDirection) trueHeading { return 91; }
@end

@implementation CLLocationManager (TemporaryLocationFix)
- (void)locationFix {
    CLLocation *location = [[CLLocation alloc] initWithLatitude:55.932 longitude:12.321];
    [[self delegate] locationManager:self didUpdateToLocation:location fromLocation:nil];

    id heading  = [[MyHeading alloc] init];
    [[self delegate] locationManager:self didUpdateHeading: heading];
}

-(void)startUpdatingHeading {
    [self performSelector:@selector(locationFix) withObject:nil afterDelay:0.1];
}

- (void)startUpdatingLocation {
    [self performSelector:@selector(locationFix) withObject:nil afterDelay:0.1];
}
@end
#endif

After iOS 5 simply include a GPX file in your project like this to have the location updated continuously Hillerød.gpx:

<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode"> 
    <wpt lat="55.93619760" lon="12.29131930"></wpt>
    <wpt lat="55.93625770" lon="12.29108330"></wpt>
    <wpt lat="55.93631780" lon="12.29078290"></wpt>
    <wpt lat="55.93642600" lon="12.29041810"></wpt>
    <wpt lat="55.93653420" lon="12.28998890"></wpt>
    <wpt lat="55.93660630" lon="12.28966710"></wpt>
    <wpt lat="55.93670240" lon="12.28936670"></wpt>
    <wpt lat="55.93677450" lon="12.28921650"></wpt>
    <wpt lat="55.93709900" lon="12.28945250"></wpt>
    <wpt lat="55.93747160" lon="12.28949540"></wpt>
    <wpt lat="55.93770000" lon="12.28966710"></wpt>
    <wpt lat="55.93785620" lon="12.28977440"></wpt>
    <wpt lat="55.93809660" lon="12.28988170"></wpt>
    <wpt lat="55.93832490" lon="12.28994600"></wpt>
    <wpt lat="55.93845710" lon="12.28996750"></wpt>
    <wpt lat="55.93856530" lon="12.29007480"></wpt>
    <wpt lat="55.93872150" lon="12.29013910"></wpt>
    <wpt lat="55.93886570" lon="12.28975290"></wpt>
    <wpt lat="55.93898590" lon="12.28955980"></wpt>
    <wpt lat="55.93910610" lon="12.28919500"></wpt>
    <wpt lat="55.93861330" lon="12.28883020"></wpt>
    <wpt lat="55.93845710" lon="12.28868000"></wpt>
    <wpt lat="55.93827680" lon="12.28850840"></wpt>
    <wpt lat="55.93809660" lon="12.28842250"></wpt>
    <wpt lat="55.93796440" lon="12.28831520"></wpt>
    <wpt lat="55.93780810" lon="12.28810070"></wpt>
    <wpt lat="55.93755570" lon="12.28790760"></wpt>
    <wpt lat="55.93739950" lon="12.28775730"></wpt>
    <wpt lat="55.93726730" lon="12.28767150"></wpt>
    <wpt lat="55.93707500" lon="12.28760710"></wpt>
    <wpt lat="55.93690670" lon="12.28734970"></wpt>
    <wpt lat="55.93675050" lon="12.28726380"></wpt>
    <wpt lat="55.93649810" lon="12.28713510"></wpt>
    <wpt lat="55.93625770" lon="12.28687760"></wpt>
    <wpt lat="55.93596930" lon="12.28679180"></wpt>
    <wpt lat="55.93587310" lon="12.28719940"></wpt>
    <wpt lat="55.93575290" lon="12.28752130"></wpt>
    <wpt lat="55.93564480" lon="12.28797190"></wpt>
    <wpt lat="55.93554860" lon="12.28833670"></wpt>
    <wpt lat="55.93550050" lon="12.28868000"></wpt>
    <wpt lat="55.93535630" lon="12.28900190"></wpt>
    <wpt lat="55.93515200" lon="12.28936670"></wpt>
    <wpt lat="55.93505580" lon="12.28958120"></wpt>
    <wpt lat="55.93481550" lon="12.29001040"></wpt>
    <wpt lat="55.93468320" lon="12.29033230"></wpt>
    <wpt lat="55.93452700" lon="12.29063270"></wpt>
    <wpt lat="55.93438280" lon="12.29095450"></wpt>
    <wpt lat="55.93425050" lon="12.29121200"></wpt>
    <wpt lat="55.93413040" lon="12.29140520"></wpt>
    <wpt lat="55.93401020" lon="12.29168410"></wpt>
    <wpt lat="55.93389000" lon="12.29189870"></wpt>
    <wpt lat="55.93372170" lon="12.29239220"></wpt>
    <wpt lat="55.93385390" lon="12.29258530"></wpt>
    <wpt lat="55.93409430" lon="12.29295010"></wpt>
    <wpt lat="55.93421450" lon="12.29320760"></wpt>
    <wpt lat="55.93433470" lon="12.29333630"></wpt>
    <wpt lat="55.93445490" lon="12.29350800"></wpt>
    <wpt lat="55.93463520" lon="12.29374400"></wpt>
    <wpt lat="55.93479140" lon="12.29410880"></wpt>
    <wpt lat="55.93491160" lon="12.29419460"></wpt>
    <wpt lat="55.93515200" lon="12.29458090"></wpt>
    <wpt lat="55.93545250" lon="12.29494570"></wpt>
    <wpt lat="55.93571690" lon="12.29505300"></wpt>
    <wpt lat="55.93593320" lon="12.29513880"></wpt>
    <wpt lat="55.93617360" lon="12.29522460"></wpt>
    <wpt lat="55.93622170" lon="12.29537480"></wpt>
    <wpt lat="55.93713510" lon="12.29505300"></wpt>
    <wpt lat="55.93776000" lon="12.29378700"></wpt>
    <wpt lat="55.93904600" lon="12.29531040"></wpt>
    <wpt lat="55.94004350" lon="12.29552500"></wpt>
    <wpt lat="55.94023570" lon="12.29561090"></wpt>
    <wpt lat="55.94019970" lon="12.29591130"></wpt>
    <wpt lat="55.94017560" lon="12.29629750"></wpt>
    <wpt lat="55.94017560" lon="12.29670520"></wpt>
    <wpt lat="55.94017560" lon="12.29713430"></wpt>
    <wpt lat="55.94019970" lon="12.29754200"></wpt>
    <wpt lat="55.94024780" lon="12.29816430"></wpt>
    <wpt lat="55.94051210" lon="12.29842180"></wpt>
    <wpt lat="55.94084860" lon="12.29820720"></wpt>
    <wpt lat="55.94105290" lon="12.29799270"></wpt>
    <wpt lat="55.94123320" lon="12.29777810"></wpt>
    <wpt lat="55.94140140" lon="12.29749910"></wpt>
    <wpt lat="55.94142550" lon="12.29726310"></wpt>
    <wpt lat="55.94147350" lon="12.29687690"></wpt>
    <wpt lat="55.94155760" lon="12.29619020"></wpt>
    <wpt lat="55.94161770" lon="12.29576110"></wpt>
    <wpt lat="55.94148550" lon="12.29531040"></wpt>
    <wpt lat="55.94093270" lon="12.29522460"></wpt>
    <wpt lat="55.94041600" lon="12.29518170"></wpt>
    <wpt lat="55.94056020" lon="12.29398010"></wpt>
    <wpt lat="55.94024780" lon="12.29352950"></wpt>
    <wpt lat="55.94001940" lon="12.29335780"></wpt>
    <wpt lat="55.93992330" lon="12.29325050"></wpt>
    <wpt lat="55.93969490" lon="12.29299300"></wpt>
    <wpt lat="55.93952670" lon="12.29277840"></wpt>
    <wpt lat="55.93928630" lon="12.29260680"></wpt>
    <wpt lat="55.93915410" lon="12.29232780"></wpt>
    <wpt lat="55.93928630" lon="12.29202740"></wpt>
    <wpt lat="55.93933440" lon="12.29174850"></wpt>
    <wpt lat="55.93947860" lon="12.29116910"></wpt>
    <wpt lat="55.93965890" lon="12.29095450"></wpt>
    <wpt lat="55.94001940" lon="12.29061120"></wpt>
    <wpt lat="55.94041600" lon="12.29084730"></wpt>
    <wpt lat="55.94076450" lon="12.29101890"></wpt>
    <wpt lat="55.94080060" lon="12.29065410"></wpt>
    <wpt lat="55.94086060" lon="12.29031080"></wpt>
    <wpt lat="55.94092070" lon="12.28990310"></wpt>
    <wpt lat="55.94099280" lon="12.28975290"></wpt>
    <wpt lat="55.94119710" lon="12.28986020"></wpt>
    <wpt lat="55.94134130" lon="12.28998890"></wpt>
    <wpt lat="55.94147350" lon="12.29007480"></wpt>
    <wpt lat="55.94166580" lon="12.29003190"></wpt>
    <wpt lat="55.94176190" lon="12.28938810"></wpt>
    <wpt lat="55.94183400" lon="12.28893750"></wpt>
    <wpt lat="55.94194220" lon="12.28850840"></wpt>
    <wpt lat="55.94199030" lon="12.28835820"></wpt>
    <wpt lat="55.94215850" lon="12.28859420"></wpt>
    <wpt lat="55.94250700" lon="12.28883020"></wpt>
    <wpt lat="55.94267520" lon="12.28893750"></wpt>
    <wpt lat="55.94284350" lon="12.28902330"></wpt>
    <wpt lat="55.94304770" lon="12.28915210"></wpt>
    <wpt lat="55.94325200" lon="12.28925940"></wpt>
    <wpt lat="55.94348030" lon="12.28953830"></wpt>
    <wpt lat="55.94366060" lon="12.28966710"></wpt>
    <wpt lat="55.94388890" lon="12.28975290"></wpt>
    <wpt lat="55.94399700" lon="12.28994600"></wpt>
    <wpt lat="55.94379280" lon="12.29065410"></wpt>
    <wpt lat="55.94364860" lon="12.29095450"></wpt>
    <wpt lat="55.94350440" lon="12.29127640"></wpt>
    <wpt lat="55.94340820" lon="12.29155540"></wpt>
    <wpt lat="55.94331210" lon="12.29198450"></wpt>
    <wpt lat="55.94315590" lon="12.29269260"></wpt>
    <wpt lat="55.94310780" lon="12.29318610"></wpt>
    <wpt lat="55.94301170" lon="12.29361530"></wpt>
    <wpt lat="55.94292760" lon="12.29408740"></wpt>
    <wpt lat="55.94290350" lon="12.29436630"></wpt>
    <wpt lat="55.94287950" lon="12.29453800"></wpt>
    <wpt lat="55.94283140" lon="12.29533190"></wpt>
    <wpt lat="55.94274730" lon="12.29606150"></wpt>
    <wpt lat="55.94278340" lon="12.29621170"></wpt>
    <wpt lat="55.94280740" lon="12.29649060"></wpt>
    <wpt lat="55.94284350" lon="12.29679100"></wpt>
    <wpt lat="55.94284350" lon="12.29734890"></wpt>
    <wpt lat="55.94308380" lon="12.29837890"></wpt>
    <wpt lat="55.94315590" lon="12.29852910"></wpt>
    <wpt lat="55.94263920" lon="12.29906550"></wpt>
    <wpt lat="55.94237480" lon="12.29910850"></wpt>
    <wpt lat="55.94220660" lon="12.29915140"></wpt>
    <wpt lat="55.94208640" lon="12.29902260"></wpt>
    <wpt lat="55.94196620" lon="12.29887240"></wpt>
    <wpt lat="55.94176190" lon="12.29794970"></wpt>
    <wpt lat="55.94156970" lon="12.29760640"></wpt>
</gpx>

I use GPSies.com to create the base file for the gpx data. A bit of cleanup is required though.

Activate by running the simulator and choosing your file


(source: castleandersen.dk)

What's the difference between compiled and interpreted language?

Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

@viewChild not working - cannot read property nativeElement of undefined

This error occurs when you're trying to target an element that is wrapped in a condition.

So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined

So use [hidden], class.show or class.hide in place of *ngIf.

<button (click)="displayMap()" class="btn btn-primary">Display Map</button>

   <div [hidden]="!display">
      <div #mapContainer id="map">Content to render when condition is true.</div>
   </div>

How to output something in PowerShell

Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta

Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.

The + $File.FullName is optional, and shows how to put a variable into the string.

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

Where does the iPhone Simulator store its data?

Where Xcode stores simulators in 2019+ Catalina, Xcode 11.0

Runtimes

$ open ~/Library/Developer/CoreSimulator/Profiles/Runtimes

For example: iOS 13.0, watchOS 6.0 These take the most space, by far. Each one can be up to ~5GB

Devices

$ open ~/Library/Developer/CoreSimulator/Devices

For example: iPhone Xr, iPhone 11 Pro Max. These are typically <15 mb each.

Explanation

Simulators are split between runtimes and devices. If you run $ xcrun simctl list you can see an overview, but if you want to find the physical location of these simulators, look in these directories I've shown.

It's totally safe to delete runtimes you don't support. You can reinstall these later if you want.

getActivity() returns null in Fragment function

Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)

Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Evaluating a mathematical expression in a string

[I know this is an old question, but it is worth pointing out new useful solutions as they pop up]

Since python3.6, this capability is now built into the language, coined "f-strings".

See: PEP 498 -- Literal String Interpolation

For example (note the f prefix):

f'{2**4}'
=> '16'

How to remove an element from a list by index

You could just search for the item you want to delete. It is really simple. Example:

    letters = ["a", "b", "c", "d", "e"]
    letters.remove(letters[1])
    print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)

Output: a c d e

Getting the IP Address of a Remote Socket Endpoint

I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient

Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))

Hope it helps! Cheers.

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

make Sublime Text 3 your default text editor: (Restart required)

defaults write com.apple.LaunchServices LSHandlers -array-add "{LSHandlerContentType=public.plain-text;LSHandlerRoleAll=com.sublimetext.3;}"

make sublime then your default git text editor git config --global core.editor "subl -W"

How to specify the JDK version in android studio?

On a Mac, you can use terminal to go to /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home (or wherever your Android SDK is installed) and enter the following in the command prompt:

./java -version

regular expression: match any word until first space

I think, a word was created with more than one letters. My suggestion is:

[^\s\s$]{2,}

Sorting a Data Table

This worked for me:

dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();

Android - get children inside a View?

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

How To have Dynamic SQL in MySQL Stored Procedure

You can pass thru outside the dynamic statement using User-Defined Variables

Server version: 5.6.25-log MySQL Community Server (GPL)

mysql> PREPARE stmt FROM 'select "AAAA" into @a';
Query OK, 0 rows affected (0.01 sec)
Statement prepared

mysql> EXECUTE stmt;
Query OK, 1 row affected (0.01 sec)

DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.01 sec)

mysql> select @a;
+------+
| @a   |
+------+
|AAAA  |
+------+
1 row in set (0.01 sec)

jquery : focus to div is not working

Focus doesn't work on divs by default. But, according to this, you can make it work:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

How to disable "prevent this page from creating additional dialogs"?

function alertWithoutNotice(message){
    setTimeout(function(){
        alert(message);
    }, 1000);
}

Running JAR file on Windows

If you have a jar file called Example.jar, follow these rules:

  1. Open a notepad.exe
  2. Write : java -jar Example.jar
  3. Save it with the extension .bat
  4. Copy it to the directory which has the .jar file
  5. Double click it to run your .jar file

pull/push from multiple remote locations

I took the liberty to expand the answer from nona-urbiz; just add this to your ~/.bashrc:

git-pullall () { for RMT in $(git remote); do git pull -v $RMT $1; done; }    
alias git-pullall=git-pullall

git-pushall () { for RMT in $(git remote); do git push -v $RMT $1; done; }
alias git-pushall=git-pushall

Usage:

git-pullall master

git-pushall master ## or
git-pushall

If you do not provide any branch argument for git-pullall then the pull from non-default remotes will fail; left this behavior as it is, since it's analogous to git.

What's the quickest way to multiply multiple cells by another number?

Select Product from formula bar in your answer cell.

Select cells you want to multiply.

Decimal precision and scale in EF Code First

Using

System.ComponentModel.DataAnnotations;

You can simply put that attribute in your model :

[DataType("decimal(18,5)")]

Conversion failed when converting the nvarchar value ... to data type int

don't use string concatenation to produce sql, you can use sp_executesql system stored prcedure to execute sql statement with parameters

create procedure getdata @ID int, @frm varchar(250), @to varchar(250) as
begin
    declare @sql nvarchar(max), @paramDefs nvarchar(max);

    set nocount on;

    set @sql = N'select EmpName, Address, Salary from Emp_Tb where @id is null or Emp_Id_Pk = @id';
    set @paramDefs = N'@id int';
    execute sp_executesql @sql, @paramDefs, @id = @ID;
end

see sp_executesql

How to return multiple values?

You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg

public class MyResult {
    int returnCode;
    String errorMessage;
    // etc
}

public MyResult someMethod() {
    // impl here
}

SQL Error: ORA-01861: literal does not match format string 01861

try to save date like this yyyy-mm-dd hh:mm:ss.ms for example: 1992-07-01 00:00:00.0 that worked for me

React Checkbox not sending onChange

In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick property as an alternative. The defaultChecked, the condition may leave a fixed state for v16 IINM.

 class CrossOutCheckbox extends Component {
      constructor(init){
          super(init);
          this.handleChange = this.handleChange.bind(this);
      }
      handleChange({target}){
          if (target.checked){
             target.removeAttribute('checked');
             target.parentNode.style.textDecoration = "";
          } else {
             target.setAttribute('checked', true);
             target.parentNode.style.textDecoration = "line-through";
          }
      }
      render(){
         return (
            <span>
              <label style={{textDecoration: this.props.complete?"line-through":""}}>
                 <input type="checkbox"
                        onClick={this.handleChange}
                        defaultChecked={this.props.complete}
                  />
              </label>
                {this.props.text}
            </span>
        )
    }
 }

I hope this helps someone in the future.

How do I unload (reload) a Python module?

It can be especially difficult to delete a module if it is not pure Python.

Here is some information from: How do I really delete an imported module?

You can use sys.getrefcount() to find out the actual number of references.

>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3

Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after

>>> del sys.modules["empty"]
>>> del empty

as the third reference is an artifact of the getrefcount() function.

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

Where can I download an offline installer of Cygwin?

I maintained rsync copy of the repository in the past.

It wasn't that big. To reduce the sync size I used rsync option --exclude (like I don't need texlive or ruby and they are not essential for base system).

Check:

Than you host this mirror via HTTP/FTP for local or organization installs:

setup.exe -p emacs --site http://localhost/cygwin

Laravel 5.4 Specific Table Migration

install this package

https://github.com/nilpahar/custom-migration/

and run this command.

php artisan migrate:custom -f migration_name

AngularJS sorting by property

AngularJS' orderBy filter does just support arrays - no objects. So you have to write an own small filter, which does the sorting for you.

Or change the format of data you handle with (if you have influence on that). An array containing objects is sortable by native orderBy filter.

Here is my orderObjectBy filter for AngularJS:

app.filter('orderObjectBy', function(){
 return function(input, attribute) {
    if (!angular.isObject(input)) return input;

    var array = [];
    for(var objectKey in input) {
        array.push(input[objectKey]);
    }

    array.sort(function(a, b){
        a = parseInt(a[attribute]);
        b = parseInt(b[attribute]);
        return a - b;
    });
    return array;
 }
});

Usage in your view:

<div class="item" ng-repeat="item in items | orderObjectBy:'position'">
    //...
</div>

The object needs in this example a position attribute, but you have the flexibility to use any attribute in objects (containing an integer), just by definition in view.

Example JSON:

{
    "123": {"name": "Test B", "position": "2"},
    "456": {"name": "Test A", "position": "1"}
}

Here is a fiddle which shows you the usage: http://jsfiddle.net/4tkj8/1/

Bootstrap Modal Backdrop Remaining

Using the code below continuously adds 7px padding on the body element every time you open and close a modal.

$('modalId').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();`

For those who still use Bootstrap 3, here is a hack'ish workaround.

$('#modalid').modal('hide');
$('.modal-backdrop').hide();
document.body.style.paddingRight = '0'
document.getElementsByTagName("body")[0].style.overflowY = "auto";

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Spring Rest POST Json RequestBody Content type not supported

In my case I had two Constructors in the bean and I had the same error. I have just deleted one of them and now the issue is fixed!

Collapse all methods in Visual Studio Code

Mac Users

Fold Commands

enter image description here

Unfold commands enter image description here

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

PostgreSQL: days/months/years between two dates

One more solution, version for the 'years' difference:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('year', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

    2

(1 row)

And the same trick for the months:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('month', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

   23

(1 row)

In real life query there can be some timestamp sequences grouped by hour/day/week/etc instead of generate_series.

This 'count(distinct(date_trunc('month', ts)))' can be used right in the 'left' side of the select:

SELECT sum(a - b)/count(distinct(date_trunc('month', c))) FROM d

I used generate_series() here just for the brevity.

SQL "between" not inclusive

I find that the best solution to comparing a datetime field to a date field is the following:

DECLARE @StartDate DATE = '5/1/2013', 
        @EndDate   DATE = '5/1/2013' 

SELECT * 
FROM   cases 
WHERE  Datediff(day, created_at, @StartDate) <= 0 
       AND Datediff(day, created_at, @EndDate) >= 0 

This is equivalent to an inclusive between statement as it includes both the start and end date as well as those that fall between.

How to update one file in a zip archive

You can use: zip -u file.zip path/file_to_update

What's the idiomatic syntax for prepending to a short python list?

What's the idiomatic syntax for prepending to a short python list?

You don't usually want to repetitively prepend to a list in Python.

If it's short, and you're not doing it a lot... then ok.

list.insert

The list.insert can be used this way.

list.insert(0, x)

But this is inefficient, because in Python, a list is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.

Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:

for (i = n; --i >= where; )
    items[i+1] = items[i];

If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque.

deque.appendleft

A collections.deque has many of the methods of a list. list.sort is an exception, making deque definitively not entirely Liskov substitutable for list.

>>> set(dir(list)) - set(dir(deque))
{'sort'}

The deque also has an appendleft method (as well as popleft). The deque is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

Also relevant is the deque's extendleft method, which iteratively prepends:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

Note that each element will be prepended one at a time, thus effectively reversing their order.

Performance of list versus deque

First we setup with some iterative prepending:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

and performance:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft you'll probably get the best performance that way.

Text Editor which shows \r\n?

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type:

https://github.com/facelessuser/RawLineEdit

How exactly does <script defer="defer"> work?

A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async

The defer and async attributes must not be specified if the src attribute is not present.


There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.


The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.


If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:

The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

While variable is not defined - wait

I prefer something simple like this:

function waitFor(variable, callback) {
  var interval = setInterval(function() {
    if (window[variable]) {
      clearInterval(interval);
      callback();
    }
  }, 200);
}

And then to use it with your example variable of someVariable:

waitFor('someVariable', function() {
  // do something here now that someVariable is defined
});

Note that there are various tweaks you can do. In the above setInterval call, I've passed 200 as how often the interval function should run. There is also an inherent delay of that amount of time (~200ms) before the variable is checked for -- in some cases, it's nice to check for it right away so there is no delay.

What is the meaning of the word logits in TensorFlow?

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

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

Regex to match only uppercase "words" with some exceptions

Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.

I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.

git reset --hard HEAD leaves untracked files behind

You might have done a soft reset at some point, you can solve this problem by doing

git add .
git reset --hard HEAD~100
git pull

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

How can I apply a border only inside a table?

this should work:

table {
 border:0;
}

table td, table th {
    border: 1px solid black;
    border-collapse: collapse;
}

edit:

i just tried it, no table border. but if i set a table border it is eliminated by the border-collapse.

this is the testfile:

<html>
<head>
<style type="text/css">
table {
    border-collapse: collapse;
    border-spacing: 0;
}


table {
    border: 0;
}
table td, table th {
    border: 1px solid black;
}


</style>
</head>
<body>
<table>
    <tr>
        <th>Heading 1</th>
        <th>Heading 2</th>
    </tr>
    <tr>
        <td>Cell (1,1)</td>
        <td>Cell (1,2)</td>
    </tr>
    <tr>
        <td>Cell (2,1)</td>
        <td>Cell (2,2)</td>
    </tr>
    <tr>
        <td>Cell (3,1)</td>
        <td>Cell (3,2)</td>
    </tr>
</table>

</body>
</html>

Node.js Mongoose.js string to ObjectId function

You can do it like this:

var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

How to compile LEX/YACC files on Windows?

You can find the latest windows version of flex & bison here: http://sourceforge.net/projects/winflexbison/

How to call loading function with React useEffect only once

function useOnceCall(cb, condition = true) {
  const isCalledRef = React.useRef(false);

  React.useEffect(() => {
    if (condition && !isCalledRef.current) {
      isCalledRef.current = true;
      cb();
    }
  }, [cb, condition]);
}

and use it.

useOnceCall(()=>{
  console.log('called');
})

or

useOnceCall(()=>{
  console.log('isLoading');
},isLoading);

Is there a TRY CATCH command in Bash

And you have traps http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html which is not the same, but other technique you can use for this purpose

while-else-loop

boolean entered = false, last;
while (( entered |= last = ( condition ) )) {
        // Do while
} if ( !entered ) {
        // Else
}

You'r welcome.

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851

How do I print the full value of a long string in gdb?

There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use x/300s your_string. The output might be a bit harder to read. For example printing a SQL query results in:

(gdb) x/300sb stmt.c_str()
0x9cd948:    "SELECT article.r"...
0x9cd958:    "owid FROM articl"...
..

Matplotlib: "Unknown projection '3d'" error

Try this:

import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d

fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")

a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

What is the difference between res.end() and res.send()?

res.send() implements res.write, res.setHeaders and res.end:

  1. It checks the data you send and sets the correct response headers.
  2. Then it streams the data with res.write.
  3. Finally, it uses res.end to set the end of the request.

There are some cases in which you will want to do this manually, for example, if you want to stream a file or a large data set. In these cases, you will want to set the headers yourself and use res.write to keep the stream flow.

How do I parallelize a simple Python loop?

Using multiple threads on CPython won't give you better performance for pure-Python code due to the global interpreter lock (GIL). I suggest using the multiprocessing module instead:

pool = multiprocessing.Pool(4)
out1, out2, out3 = zip(*pool.map(calc_stuff, range(0, 10 * offset, offset)))

Note that this won't work in the interactive interpreter.

To avoid the usual FUD around the GIL: There wouldn't be any advantage to using threads for this example anyway. You want to use processes here, not threads, because they avoid a whole bunch of problems.

Integration Testing POSTing an entire object to Spring MVC controller

I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.

First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.

In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:

    @Test
    public void testFormEdit() throws Exception {
        getMockMvc()
                .perform(
                        addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
                                .param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
    }

    private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());

        Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);

        for (Entry<String, ?> entry : propertyValues.entrySet()) {
            builder.param(entry.getKey(),
                    Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
        }

        return builder;
    }

    private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(dateFormat);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JodaModule());

        TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};

        Map<String, ?> returnValues = mapper.convertValue(object, typeRef);

        return returnValues;

    }

How can I get name of element with jQuery?

You should use attr('name') like this

 $('#yourid').attr('name')

you should use an id selector, if you use a class selector you encounter problems because a collection is returned

MySQL - Replace Character in Columns

Just running the SELECT statement will have no effect on the data. You have to use an UPDATE statement with the REPLACE to make the change occur:

UPDATE photos
   SET caption = REPLACE(caption,'"','\'')

Here is a working sample: http://sqlize.com/7FjtEyeLAh

Using Django time/date widgets in custom form

For Django >= 2.0

Note: Using admin widgets for date-time fields is not a good idea as admin style-sheets can conflict with your site style-sheets in case you are using bootstrap or any other CSS frameworks. If you are building your site on bootstrap use my bootstrap-datepicker widget django-bootstrap-datepicker-plus.

Step 1: Add javascript-catalog URL to your project's (not app's) urls.py file.

from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]

Step 2: Add required JavaScript/CSS resources to your template.

<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static '/admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static '/admin/css/widgets.css' %}">
<style>.calendar>table>caption{caption-side:unset}</style><!--caption fix for bootstrap4-->
{{ form.media }}        {# Form required JS and CSS #}

Step 3: Use admin widgets for date-time input fields in your forms.py.

from django.contrib.admin import widgets
from .models import Product

class ProductCreateForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'publish_date', 'publish_time', 'publish_datetime']
        widgets = {
            'publish_date': widgets.AdminDateWidget,
            'publish_time': widgets.AdminTimeWidget,
            'publish_datetime': widgets.AdminSplitDateTime,
        }

Is there a way to split a widescreen monitor in to two or more virtual monitors?

Right now, I'm using twinsplay to organize my windows side by side.

I tried Winsplit before, but I couldn't get it to work because the default hotkeys ( Ctrl-Alt-Left, Ctrl-Alt-Right ) clashed with the graphics card hotkeys for rotating my screen and setting different hotkeys just didn't work. Twinsplay just worked for me out of the box.

Another nice thing about twinsplay is that it also allows me to save and restore windows "sessions" - so I can save my work environment ( eclipse, total commander, visual studio, msdn, outlook, firefox ) before turning off the computer at night and then quickly get back to it in the morning.

How to query between two dates using Laravel and Eloquent?

I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

You will also need to use Carbon

use Carbon\Carbon;

Set default value of an integer column SQLite

A column with default value:

CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)

<DefaultValue> is a placeholder for a:

  • value literal
  • ( expression )

Examples:

Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))

Calculate a Running Total in SQL Server

Using join Another variation is to use join. Now the query could look like:

    SELECT a.id, a.value, SUM(b.Value)FROM   RunTotalTestData a,
    RunTotalTestData b
    WHERE b.id <= a.id
    GROUP BY a.id, a.value 
    ORDER BY a.id;

for more you can visite this link http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

Working with dictionaries/lists in R

The reason for using dictionaries in the first place is performance. Although it is correct that you can use named vectors and lists for the task the issue is that they are becoming quite slow and memory hungry with more data.

Yet what many people don't know is that R has indeed an inbuilt dictionary data structure: environments with the option hash = TRUE

See the following example for how to make it work:

# vectorize assign, get and exists for convenience
assign_hash <- Vectorize(assign, vectorize.args = c("x", "value"))
get_hash <- Vectorize(get, vectorize.args = "x")
exists_hash <- Vectorize(exists, vectorize.args = "x")

# keys and values
key<- c("tic", "tac", "toe")
value <- c(1, 22, 333)

# initialize hash
hash = new.env(hash = TRUE, parent = emptyenv(), size = 100L)
# assign values to keys
assign_hash(key, value, hash)
## tic tac toe 
##   1  22 333
# get values for keys
get_hash(c("toe", "tic"), hash)
## toe tic 
## 333   1
# alternatively:
mget(c("toe", "tic"), hash)
## $toe
## [1] 333
## 
## $tic
## [1] 1
# show all keys
ls(hash)
## [1] "tac" "tic" "toe"
# show all keys with values
get_hash(ls(hash), hash)
## tac tic toe 
##  22   1 333
# remove key-value pairs
rm(list = c("toe", "tic"), envir = hash)
get_hash(ls(hash), hash)
## tac 
##  22
# check if keys are in hash
exists_hash(c("tac", "nothere"), hash)
##     tac nothere 
##    TRUE   FALSE
# for single keys this is also possible:
# show value for single key
hash[["tac"]]
## [1] 22
# create new key-value pair
hash[["test"]] <- 1234
get_hash(ls(hash), hash)
##  tac test 
##   22 1234
# update single value
hash[["test"]] <- 54321
get_hash(ls(hash), hash)
##   tac  test 
##    22 54321

Edit: On the basis of this answer I wrote a blog post with some more context: http://blog.ephorie.de/hash-me-if-you-can