Programs & Examples On #Kill

Kill is an operation of removing an object or process from memory so that other processes/variables can use them.

Why number 9 in kill -9 command in unix?

Both are same as kill -sigkill processID, kill -9 processID. Its basically for forced termination of the process.

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

How can I kill a process by name instead of PID?

A bit longer alternative:

kill `pidof firefox`

Kill process by name?

this worked for me in windows 7

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")

Is there any way to kill a Thread?

It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...

How do I kill an Activity when the Back button is pressed?

add this to your activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

How can I stop a running MySQL query?

Connect to mysql

mysql -uusername -p  -hhostname

show full processlist:

mysql> show full processlist;
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| Id      | User   | Host              | db      | Command | Time | State | Info             |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| 9255451 | logreg | dmin001.ops:37651 | logdata | Query   |    0 | NULL  | show processlist |
+---------+--------+-------------------+---------+---------+------+-------+------------------+

Kill the specific query. Here id=9255451

mysql> kill 9255451;

If you get permission denied, try this SQL:

CALL mysql.rds_kill(9255451)

Kill detached screen session

== ISSUE THIS COMMAND
[xxx@devxxx ~]$ screen -ls


== SCREEN RESPONDS
There are screens on:
        23487.pts-0.devxxx      (Detached)
        26727.pts-0.devxxx      (Attached)
2 Sockets in /tmp/uscreens/S-xxx.


== NOW KILL THE ONE YOU DONT WANT
[xxx@devxxx ~]$ screen -X -S 23487.pts-0.devxxx kill


== WANT PROOF?
[xxx@devxxx ~]$ screen -ls
There is a screen on:
        26727.pts-0.devxxx      (Attached)
1 Socket in /tmp/uscreens/S-xxx.

What killed my process and why?

I encountered this problem lately. Finally, I found my processes were killed just after Opensuse zypper update was called automatically. To disable zypper update solved my problem.

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I just had the same happen on me when I tried to run a python script from a shared folder in VirtualBox within the new Ubuntu 20.04 LTS. Python bailed with Killed while loading my own personal library. When I moved the folder to a local directory, the issue went away. It appears that the Killed stop happened during the initial imports of my library as I got messages of missing libraries once I moved the folder over.

The issue went away after I restarted my computer.

Therefore, people may want to try moving the program to a local directory if its over a share of some kind or it could be a transient problem that just requires a reboot of the OS.

how to kill hadoop jobs

Depending on the version, do:

version <2.3.0

Kill a hadoop job:

hadoop job -kill $jobId

You can get a list of all jobId's doing:

hadoop job -list

version >=2.3.0

Kill a hadoop job:

yarn application -kill $ApplicationId

You can get a list of all ApplicationId's doing:

yarn application -list

How do I kill a process using Vb.NET or C#?

I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process

How to kill all processes matching a name?

use pgrep

kill -9 $(pgrep amarok)

linux: kill background task

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

How to kill a nodejs process in Linux?

In order to kill use: killall -9 /usr/bin/node

To reload use: killall -12 /usr/bin/node

How can I kill all sessions connecting to my oracle database?

I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html

select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;

Then ran:

Alter System Kill Session '<value from ss above>'
;

To kill individual sessions.

Most efficient way to prepend a value to an array

There is special method:

a.unshift(value);

But if you want to prepend several elements to array it would be faster to use such a method:

var a = [1, 2, 3],
    b = [4, 5];

function prependArray(a, b) {
    var args = b;
    args.unshift(0);
    args.unshift(0);
    Array.prototype.splice.apply(a, args);
}

prependArray(a, b);
console.log(a); // -> [4, 5, 1, 2, 3]

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

How to run TypeScript files from command line?

Just helpful information - here is newest TypeScript / JavaScript runtime Deno.

It was created by the creator of node Ryan Dahl, based on what he would do differently if he could start fresh.

jQuery delete confirmation box

Simply works as:

$("a. close").live("click",function(event){
     return confirm("Do you want to delete?");
});

flutter corner radius with transparent background

Use transparent background color for the modalbottomsheet and give separate color for box decoration


   showModalBottomSheet(
      backgroundColor: Colors.transparent,
      context: context, builder: (context) {
    return Container(

      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft:Radius.circular(40) ,
            topRight: Radius.circular(40)
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
      child: Settings_Form(),
    );
  });

Remove characters from a String in Java

Strings in java are immutable. That means you need to create a new string or overwrite your old string to achieve the desired affect:

id = id.replace(".xml", "");

Invariant Violation: _registerComponent(...): Target container is not a DOM element

/index.html

<!doctype html>
<html>
  <head>
    <title>My Application</title>
    <!-- load application bundle asynchronously -->
    <script async src="/app.js"></script>
    <style type="text/css">
      /* pre-rendered critical path CSS (see isomorphic-style-loader) */
    </style>
  </head>
  <body>
    <div id="app">
      <!-- pre-rendered markup of your JavaScript app (see isomorphic apps) -->
    </div>
  </body>
</html>

/app.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

function run() {
  ReactDOM.render(<App />, document.getElementById('app'));
}

const loadedStates = ['complete', 'loaded', 'interactive'];

if (loadedStates.includes(document.readyState) && document.body) {
  run();
} else {
  window.addEventListener('DOMContentLoaded', run, false);
}

(IE9+)

Note: Having <script async src="..."></script> in the header ensures that the browser will start downloading JavaScript bundle before HTML content is loaded.

Source: React Starter Kit, isomorphic-style-loader

Remove HTML tags from string including &nbsp in C#

I took @Ravi Thapliyal's code and made a method: It is simple and might not clean everything, but so far it is doing what I need it to do.

public static string ScrubHtml(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
    var step2 = Regex.Replace(step1, @"\s{2,}", " ");
    return step2;
}

jQuery map vs. each

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array. For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

You'll also note that the this is not mapped in the map function. You will have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.

Apply jQuery datepicker to multiple instances

I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js

// this.element.on('click', $.proxy(this.show, this));

how to make log4j to write to the console as well

This works well for console in debug mode

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

How do you test to see if a double is equal to NaN?

Try Double.isNaN():

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

Pure Lua uses only what is in ANSI standard C. Luiz Figuereido's lposix module contains much of what you need to do more systemsy things.

Javascript Confirm popup Yes, No button instead of OK and Cancel

the very specific answer to the point is confirm dialogue Js Function:

confirm('Do you really want to do so');

It show dialogue box with ok cancel buttons,to replace these button with yes no is not so simple task,for that you need to write jQuery function.

Angular 2 How to redirect to 404 or other path if the path does not exist

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

import { Router } from '@angular/router';

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

Removing an element from an Array (Java)

I hope you use the java collection / java commons collections!

With an java.util.ArrayList you can do things like the following:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);

Template not provided using create-react-app

I fix this issue on Mac by uninstalling create-react-app from global npm lib, that's basically what said, just try to do, you need also do sudo:

sudo npm uninstall -g create-react-app

Then simply run:

npx create-react-app my-app-name

Now should be all good and get the folder structures as below:

template not provided using create react app

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

how to overwrite css style

Using !important is not recommended but in this situation I think you should -

Write this in your internal CSS -

.flex-control-thumbs li {
  width: auto !important;
  float: none !important;
}

What is a unix command for deleting the first N characters of a line?

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

How to sum digits of an integer in java?

Mine is more simple than the others hopefully you can understand this if you are a some what new programmer like myself.

import java.util.Scanner;
import java.lang.Math;

public class DigitsSum {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int digit = 0;
        System.out.print("Please enter a positive integer: ");
        digit = in.nextInt();
        int D1 = 0;
        int D2 = 0;
        int D3 = 0;
        int G2 = 0;
        D1 = digit / 100;
        D2 = digit % 100;
        G2 = D2 / 10;
        D3 = digit % 10;


        System.out.println(D3 + G2 + D1);

    }
}

Convert International String to \u Codes in java

There is an Open Source java library MgntUtils that has a Utility that converts Strings to unicode sequence and vise versa:

result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);

The output of this code is:

\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World

The library can be found at Maven Central or at Github It comes as maven artifact and with sources and javadoc

Here is javadoc for the class StringUnicodeEncoderDecoder

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

std::thread thread([&thread]() {
    sleep(3);
    thread.detach();
});

while(thread.joinable())
    sleep(1);

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

Format JavaScript date as yyyy-mm-dd

Reformatting a date string is fairly straightforward, e.g.

_x000D_
_x000D_
var s = 'Sun May 11,2014';_x000D_
_x000D_
function reformatDate(s) {_x000D_
  function z(n){return ('0' + n).slice(-2)}_x000D_
  var months = [,'jan','feb','mar','apr','may','jun',_x000D_
                 'jul','aug','sep','oct','nov','dec'];_x000D_
  var b = s.split(/\W+/);_x000D_
  return b[3] + '-' +_x000D_
    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +_x000D_
    z(b[2]);_x000D_
}_x000D_
_x000D_
console.log(reformatDate(s));
_x000D_
_x000D_
_x000D_

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

How to get Git to clone into current directory

Removing with

rm -rf .*

may get you into trouble or some more errors.

If you have /path/to/folder, and would like to remove everything inside, but not that folder, just run:

rm -rf /path/to/folder/*

"message failed to fetch from registry" while trying to install any module

The only thing that worked for me on Elementary OS Luna, a Ubuntu Fork. I am on x86 architecture. I tried all the answers here but finally decided to install it from source.

First, make sure its not installed using the package manager:

sudo apt-get purge nodejs npm -y

I went to the download page to lookup the latest source & download it, http://nodejs.org/download/. You can use curl, wget or your browser to get it:

wget http://nodejs.org/dist/v0.10.34/node-v0.10.34.tar.gz
tar -xvf node-v0.10.34.tar.gz 
cd node-v0.10.34
./configure
make
sudo make install

The make might take a while. When done, you should have node and npm installed and working in your /usr/local/bin directory which should be already on your path. You should verify where it lives:

which npm node

I also had to change the permissions to get it to work:

sudo chown -R $USER /usr/local

If it didn't work check your path:

echo $PATH

Note that installing it this way, it will not be managed by apt-get package manager. Cheers!

Which version of Python do I have installed?

In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Create a view with ORDER BY clause

As one of the comments in this posting suggests using stored procedures to return the data... I think that is the best answer. In my case what I did is wrote a View to encapsulate the query logic and joins, then I wrote a Stored Proc to return the data sorted and the proc also includes other enhancement features such as parameters for filtering the data.

Now you have to option to query the view, which allows you to manipulate the data further. Or you have the option to execute the stored proc, which is quicker and more precise output.

STORED PROC Execution to query data

exec [olap].[uspUsageStatsLogSessionsRollup]

VIEW Definition

USE [DBA]
GO

/****** Object:  View [olap].[vwUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 10:10:06 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--USE DBA
-- select * from olap.UsageStatsLog_GCOP039 where CubeCommand='[ORDER_HISTORY]'
;

ALTER VIEW [olap].[vwUsageStatsLogSessionsRollup] as
(
    SELECT --*
        t1.UsageStatsLogDate
        , COALESCE(CAST(t1.UsageStatsLogDate AS nvarchar(100)), 'TOTAL- DATES:') AS UsageStatsLogDate_Totals
        , t1.ADUserNameDisplayNEW
        , COALESCE(t1.ADUserNameDisplayNEW, 'TOTAL- USERS:') AS ADUserNameDisplay_Totals
        , t1.CubeCommandNEW
        , COALESCE(t1.CubeCommandNEW, 'TOTAL- CUBES:') AS CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
    FROM
    (
        select 
            CAST(olapUSL.UsageStatsLogTime as date) as UsageStatsLogDate
            , olapUSL.ADUserNameDisplayNEW
            , olapUSL.CubeCommandNEW
            , count(*) SessionsCount
            , count(distinct olapUSL.ADUserNameDisplayNEW) UsersCount
            , count(distinct olapUSL.CubeCommandNEW) CubesCount
        from 
            olap.vwUsageStatsLog olapUSL
        where CubeCommandNEW != '[]'
        GROUP BY CUBE(CAST(olapUSL.UsageStatsLogTime as date), olapUSL.ADUserNameDisplayNEW, olapUSL.CubeCommandNEW )
            ----GROUP BY 
            ------GROUP BY GROUPING SETS
            --------GROUP BY ROLLUP
    ) t1

    --ORDER BY
    --  t1.UsageStatsLogDate DESC
    --  , t1.ADUserNameDisplayNEW
    --  , t1.CubeCommandNEW
)
;


GO

STORED PROC Definition

USE [DBA]
GO

/****** Object:  StoredProcedure [olap].[uspUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 9:39:31 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:      BRIAN LOFTON
-- Create date: 2/19/2019
-- Description: This proceedured returns data from a view with sorted results and an optional date range filter.
-- =============================================
ALTER PROCEDURE [olap].[uspUsageStatsLogSessionsRollup]
    -- Add the parameters for the stored procedure here
    @paramStartDate date = NULL,
    @paramEndDate date = NULL,
    @paramDateTotalExcluded as int = 0,
    @paramUserTotalExcluded as int = 0,
    @paramCubeTotalExcluded as int = 0
AS

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @varStartDate as date 
        = CASE  
            WHEN @paramStartDate IS NULL THEN '1900-01-01' 
            ELSE @paramStartDate 
        END
    DECLARE @varEndDate as date 
        = CASE  
            WHEN @paramEndDate IS NULL THEN '2100-01-01' 
            ELSE @paramStartDate 
        END

    -- Return Data from this statement
    SELECT 
        t1.UsageStatsLogDate_Totals
        , t1.ADUserNameDisplay_Totals
        , t1.CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
        -- Fields with NULL in the totals
            --  , t1.CubeCommandNEW
            --  , t1.ADUserNameDisplayNEW
            --  , t1.UsageStatsLogDate
    FROM 
        olap.vwUsageStatsLogSessionsRollup t1
    WHERE

        (
            --t1.UsageStatsLogDate BETWEEN @varStartDate AND @varEndDate
            t1.UsageStatsLogDate BETWEEN '1900-01-01' AND '2100-01-01'
            OR t1.UsageStatsLogDate IS NULL
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramDateTotalExcluded=1 AND UsageStatsLogDate_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramUserTotalExcluded=1 AND ADUserNameDisplay_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramCubeTotalExcluded=0
            OR (@paramCubeTotalExcluded=1 AND CubeCommand_Totals NOT LIKE '%TOTAL-%')
        )
    ORDER BY
            t1.UsageStatsLogDate DESC
            , t1.ADUserNameDisplayNEW
            , t1.CubeCommandNEW

END


GO

Can a java lambda have more than 1 parameter?

You could also use jOOL library - https://github.com/jOOQ/jOOL

It has already prepared function interfaces with different number of parameters. For instance, you could use org.jooq.lambda.function.Function3, etc from Function0 up to Function16.

MySQL - Trigger for updating same table after insert

It seems that you can't do all this in a trigger. According to the documentation:

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

According to this answer, it seems that you should:

create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.

With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.

Connect to Amazon EC2 file directory using Filezilla and SFTP

In my case, Filezilla sends the AWS ppk file to every other FTP server I try to securely connect to.

That's crazy. There's a workaround as written below but it's ugly.

It does not behave well as @Lucio M pointed out.

From this discussion: https://forum.filezilla-project.org/viewtopic.php?t=30605

n0lqu:

Agreed. However, given I can't control the operation of the server, is there any way to specify within FileZilla that a site should authenticate with a password rather than key, or vice-versa? Or tell it to try password first, then key only if password fails? It appears to me it's trying key first, and then not getting a chance to try password.

botg(Filezilla admin) replied:

There's no such option.

n0lqu:

Could such an option be added, or are there any good workarounds anyone can recommend? Right now, the only workaround I know is to delete the key from general preferences, add it back only when connecting to the specific site that requires it, then deleting it again when done so it doesn't mess up other sites.

botg:

Right now you could have two FileZilla instances with separate config dirs (e. g. one installed and one portable).

timboskratch:

I just had this same issue today and managed to resolve it by changing the "logon type" of the connection using a password in the site manager. Instead of "Normal" I could select either "Interactive" or "Ask for Password" (not really sure what the difference is) and then when I tried to connect to the site again it gave me a prompt to enter my password and then connected successfully. It's not ideal as it means you have to remember and re-type you password every time you connect, but better than having to install 2 instances of FileZilla. I totally agree that it would be very useful in the Site Manager to have full options of how you would like FileZilla to connect to each site which is set up (whether to use a password, key, etc.) Hope this is helpful! Tim

Also see: https://forum.filezilla-project.org/viewtopic.php?t=34676

So, it seems:

For multiple FTP sites with keys / passwords, use multiple Filezilla installs, OR, use the same ppk key for all servers.

I wish there was a way to tell FileZilla which ppk is for which site in Site Manger

Launch Image does not show up in my iOS App

I had a very strange bug. Apparently my launch image source was only set for debug configuration and not release. This resulted in my launch screen appearing when running debug configuration, but when I changed to release I just got a black screen.

I fixed this when I changed my build configuration to release the Launch Image Source button appeared and I had to choose Use Asset Catalog again.

For those who are curious, this is what my project.pbxproj looked like.

...
...
...
XXXXXXXXXXXXXXXXXXXXXXXX /* Release */ = {
            isa = XCBuildConfiguration;
            buildSettings = {
                ALWAYS_SEARCH_USER_PATHS = NO;
                ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
                ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; <---THIS LINE WAS MISSING
...
...
...

Change visibility of ASP.NET label with JavaScript

If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:

<asp:Label runat="server" id="Label1" style="display: none;" />

Then, you could make it visible on the client side with:

document.getElementById('Label1').style.display = 'inherit';

You could make it hidden again with:

document.getElementById('Label1').style.display = 'none';

Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.

How do I grep recursively?

For .gz files, recursively scan all files and directories Change file type or put *

find . -name \*.gz -print0 | xargs -0 zgrep "STRING"

Passing parameters on button action:@selector

You can set tag of the button and access it from sender in action

[btnHome addTarget:self action:@selector(btnMenuClicked:)     forControlEvents:UIControlEventTouchUpInside];
                    btnHome.userInteractionEnabled = YES;
                    btnHome.tag = 123;

In the called function

-(void)btnMenuClicked:(id)sender
{
[sender tag];

    if ([sender tag] == 123) {
        // Do Anything
    }
}

Proper use of 'yield return'

And what about this?

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList();
    }
}

I guess this is much cleaner. I do not have VS2008 at hand to check, though. In any case, if Products implements IEnumerable (as it seems to - it is used in a foreach statement), I'd return it directly.

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I faced the same issue with grpc module and in my case, I was using electron and have set a wrong electron version in the env variable "export npm_config_target=1.2.3", setting it to the electron version I am using resolved the issue on my end. Hope this helps someone who set env variables as given here (https://electronjs.org/docs/tutorial/using-native-node-modules#the-npm-way)

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Just to add on to the topic of for in/for/$.each, I added a jsperf test case for using $.each vs for in: http://jsperf.com/each-vs-for-in/2

Different browsers/versions handle it differently, but it seems $.each and straight out for in are the cheapest options performance-wise.

If you're using for in to iterate through an associative array/object, knowing what you're after and ignoring everything else, use $.each if you use jQuery, or just for in (and then a break; once you've reached what you know should be the last element)

If you're iterating through an array to perform something with each key pair in it, should use the hasOwnProperty method if you DON'T use jQuery, and use $.each if you DO use jQuery.

Always use for(i=0;i<o.length;i++) if you don't need an associative array though... lol chrome performed that 97% faster than a for in or $.each

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

How can I make an svg scale with its parent container?

Messing around & found this CSS seems to contain the SVG in Chrome browser up to the point where the container is larger than the image:

div.inserted-svg-logo svg { max-width:100%; }

Also seems to be working in FF + IE 11.

How to check if a Docker image with a specific tag exist locally?

Just a bit from me to very good readers:

Build

#!/bin/bash -e
docker build -t smpp-gateway smpp
(if  [ $(docker ps -a | grep smpp-gateway | cut -d " " -f1) ]; then \
  echo $(docker rm -f smpp-gateway); \
else \
  echo OK; \
fi;);
docker run --restart always -d --network="host" --name smpp-gateway smpp-gateway:latest

Watch

docker logs --tail 50 --follow --timestamps smpp-gateway

Run

sudo docker exec -it \
$(sudo docker ps | grep "smpp-gateway:latest" | cut -d " " -f1) \
/bin/bash

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

Remove Duplicate objects from JSON Array

You can use lodash, download here (4.17.15)

Example code:

var object = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(object, _.isEqual);

// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

Inputting a default image in case the src attribute of an html <img> is not valid?

If you are using Angular 1.x you can include a directive that will allow you to fallback to any number of images. The fallback attribute supports a single url, multiple urls inside an array, or an angular expression using scope data:

<img ng-src="myFirstImage.png" fallback="'fallback1.png'" />
<img ng-src="myFirstImage.png" fallback="['fallback1.png', 'fallback2.png']" />
<img ng-src="myFirstImage.png" fallback="myData.arrayOfImagesToFallbackTo" />

Add a new fallback directive to your angular app module:

angular.module('app.services', [])
    .directive('fallback', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var errorCount = 0;

                // Hook the image element error event
                angular.element(element).bind('error', function (err) {
                    var expressionFunc = $parse(attrs.fallback),
                        expressionResult,
                        imageUrl;

                    expressionResult = expressionFunc(scope);

                    if (typeof expressionResult === 'string') {
                        // The expression result is a string, use it as a url
                        imageUrl = expressionResult;
                    } else if (typeof expressionResult === 'object' && expressionResult instanceof Array) {
                        // The expression result is an array, grab an item from the array
                        // and use that as the image url
                        imageUrl = expressionResult[errorCount];
                    }

                    // Increment the error count so we can keep track
                    // of how many images we have tried
                    errorCount++;
                    angular.element(element).attr('src', imageUrl);
                });
            }
        };
    }])

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

I have removed the scope and then used a maven update to solve this problem.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    **<!-- <scope>provided</scope> -->**
</dependency>

The jstl lib is not present in the tomcat lib folder.So we have to include it. I don't understand why we are told to keep both servlet-api and jstl's scope as provided.

Embed YouTube Video with No Ads

I'd just like to add, and please correct me if I'm wrong, that when I embed the HTML5 version of the videos, it doesn't play ads on top.

Not sure if this will ever change. They're probably just trying to work out the best way to show ads on the HTML5 player.

How to prevent user from typing in text field without disabling the field?

If you want to prevent the user from adding anything, but provide them with the ability to erase characters:

_x000D_
_x000D_
<input value="CAN'T ADD TO THIS" maxlength="0" />
_x000D_
_x000D_
_x000D_

Setting the maxlength attribute of an input to "0" makes it so that the user is unable to add content, but still erase content as they wish.


But If you want it to be truly constant and unchangeable:

_x000D_
_x000D_
<input value="THIS IS READONLY" onkeydown="return false" />
_x000D_
_x000D_
_x000D_

Setting the onkeydown attribute to return false makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.

Multiple inheritance for an anonymous class

// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let's provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println("Anonymous something!"); }
    }
);

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

How to check if an element is in an array

For those who came here looking for a find and remove an object from an array:

Swift 1

if let index = find(itemList, item) {
    itemList.removeAtIndex(index)
}

Swift 2

if let index = itemList.indexOf(item) {
    itemList.removeAtIndex(index)
}

Swift 3, 4

if let index = itemList.index(of: item) {
    itemList.remove(at: index)
}

Swift 5.2

if let index = itemList.firstIndex(of: item) {
    itemList.remove(at: index)
}

Warning: comparison with string literals results in unspecified behaviour

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same (which they won't be in this case).

args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<".

The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location).

The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

What are WSDL, SOAP and REST?

SOAP -> SOAP(Simple object access protocal) is the application level protocal created for machine to machine interaction. Protocol defines standard rules. All the parties who are using the particular protocol should adhere to the protocol rules. Like TCP, It unwinds at transport layer, The SOAP protocol will be understood by Application layer( any application which supports SOAP - Axis2, .Net).

WSDL -> SOAP message consist of SoapEnevelope->SoapHeader and SoapBody. It doesn't define what would be message format? what are all the transports(HTTP,JMS) it supports? without this info, It is hard for any client who wants to consume the particular web service to construct the SOAP message. Even if they do, they won't be sure, it'll work all the time. WSDL is the rescue. WSDL (Web Service description Language) defines the operations, message formats and transport details for the SOAP message.

REST -> REST(Representational state transfer) is based on the Transport. Unlike SOAP which targets the actions, REST concerns more on the resources. REST locates the resources by using URL (example -http://{serverAddress}/employees/employeeNumber/12345) and it depends on the transport protocol( with HTTP - GET,POST, PUT, DELETE,...) for the actions to be performed on the resources. The REST service locates the resource based on the URL and perform the action based on the transport action verb. It is more of architectural style and conventions based.

How to resolve "Waiting for Debugger" message?

Android Studio 1.2.2 on Mac OS 10.10 Same problem as others have reported. I closed Android Studio, then checked from command line in terminal:

ps -efw|grep -i android

This reported a java process (.gradle/daemon) associated with Android Studio. I killed this process, restarted Android Studio, and the problem went away.

Symbolicating iPhone App Crash Reports

Steps to analyze crash report from apple:

  1. Copy the release .app file which was pushed to the appstore, the .dSYM file that was created at the time of release and the crash report receive from APPLE into a FOLDER.

  2. OPEN terminal application and go to the folder created above (using cd command)

  3. Run atos -arch armv7 -o APPNAME.app/APPNAME MEMORY_LOCATION_OF_CRASH. The memory location should be the one at which the app crashed as per the report.

Ex: atos -arch armv7 -o 'APPNAME.app'/'APPNAME' 0x0003b508

This would show you the exact line, method name which resulted in crash.

Ex: [classname functionName:]; -510

Symbolicating IPA

if we use IPA for symbolicating - just rename the extention .ipa with .zip , extract it then we can get a Payload Folder which contain app. In this case we don't need .dSYM file.

Note

This can only work if the app binary does not have symbols stripped. By default release builds stripped the symbols. We can change it in project build settings "Strip Debug Symbols During Copy" to NO.

More details see this post

How do I edit $PATH (.bash_profile) on OSX?

For beginners: To create your .bash_profile file in your home directory on MacOS, run:

nano ~/.bash_profile

Then you can paste in the following:

https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054

As you can see, it includes some example aliases and an environment variable at the bottom.

One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O) and Exit (Ctrl-X). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.

Javascript equivalent of php's strtotime()?

I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method

var d=new Date("October 13, 1975 11:13:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");

Does this work?

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

Android device does not show up in adb list

I had similar problem with my "Xiaomi Redmi Note 4" and tried almost 10 solutions I found over internet, but none of them helped my case. I've posted this answer to help someones like myself.

Installing "Intel USB Driver for Android Devices" totally solved my problem. It's described completely here.

Easy way to password-protect php page

</html>
<head>
  <title>Nick Benvenuti</title>
  <link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
  <link rel="stylesheet" href="CSS/main.css">
  <link rel="stylesheet" href="CSS/normalize.css">
  <script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
  <script type="text/javascript">
  function tester() {
  window.location.href="admin.php";
  }
  function phpshower() {
  document.getElementById("phplogger").classList.toggle('shower');
  document.getElementById("phplogger").classList.remove('hider');
  }
  function phphider() {
  document.getElementById("phplogger").classList.toggle('hider');
  document.getElementById("phplogger").classList.remove('shower');
  }
</script>
<?php 
//if "login" variable is filled out, send email
  if (isset($_REQUEST['login']))  {

  //Login info
  $passbox = $_REQUEST['login'];
  $password = 'blahblahyoudontneedtoknowmypassword';

  //Login
  if($passbox == $password) {

  //Login response
  echo "<script text/javascript> phphider(); </script>";
  }
 }
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
 <form method="post">
  Password: <input name="login" type="text" /><br />
  <input type="submit" value="Login" id="submit-button" />
  </form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>

Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.

  /*PHP CONTENT STARTS HERE*/
  .hider {
  visibility:hidden;
  display:none;
  }

  .shower {
  visibility:visible;
  }

  #phplogger {
  background-color:#333;
  color:blue;
  position:absolute;
  height:100%;
  width:100%;
  margin:0;
  top:0;
  bottom:0;
  }
  /*PHP CONTENT ENDS HERE*/

Playing .mp3 and .wav in Java?

I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)

Here is a minimalistic usage example:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Required imports:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

C#: how to get first char of a string?

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

Cannot find module '@angular/compiler'

I just run npm install and then ok.

brew install mysql on macOS

None of the above answers (or any of the dozens of answers I saw elsewhere) worked for me when using brew with the most recent version of mysql and yosemite. I ended up installing a different mysql version via brew.

Specifying an older version by saying (for example)

brew install mysql56

Worked for me. Hope this helps someone. This was a frustrating problem that I felt like I was stuck on forever.

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Count the number of items in my array list

You want to count the number of itemids in your array. Simply use:

int counter=list.size();

Less code increases efficiency. Do not re-invent the wheel...

How to write a file or data to an S3 object using boto3

In boto 3, the 'Key.set_contents_from_' methods were replaced by

For example:

import boto3

some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'

# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)

# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:

Storing Data

Storing data from a file, stream, or string is easy:

# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')

# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))

"rm -rf" equivalent for Windows?

RMDIR [/S] [/Q] [drive:]path

RD [/S] [/Q] [drive:]path

  • /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.

  • /Q Quiet mode, do not ask if ok to remove a directory tree with /S

"Warning: iPhone apps should include an armv6 architecture" even with build config set

If using Xcode 4.2 or higher, try the following:

  1. Click your Project name (in the left column), followed by the Target:

    enter image description here

  2. Click the 'Build Settings' tab (in the right column):

    enter image description here

  3. Click the 'Release' or 'Distribution' row under 'Architectures', and choose 'Other...':

    enter image description here

  4. Double click the highlighted row named '$(ARCHS_STANDARD_32_BIT)' in the popover that appears, and replace it by typing 'armv6'. Then add a new row with the plus button in the bottom left of the popover, and type 'armv7', then click Done:

    enter image description here

Update: you should add armv7s to target the iPhone 5 as well. (And drop armv6 if building with Xcode 4.5 or higher, which no longer supports armv6.)

That's it. You should now be able to build/archive without generating errors.

If it still doesn't work, see this answer from justinxreese, which suggests adding entries for armv6 and armv7 under "Required Device Capabilities" in your info.plist file.

Jupyter/IPython Notebooks: Shortcut for "run all"?

As of 5.5 you can run Kernel > Restart and Run All

What is monkey patching?

What is a monkey patch?

Simply put, monkey patching is making changes to a module or class while the program is running.

Example in usage

There's an example of monkey-patching in the Pandas documentation:

import pandas as pd
def just_foo_cols(self):
    """Get a list of column names containing the string 'foo'

    """
    return [x for x in self.columns if 'foo' in x]

pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method

To break this down, first we import our module:

import pandas as pd

Next we create a method definition, which exists unbound and free outside the scope of any class definitions (since the distinction is fairly meaningless between a function and an unbound method, Python 3 does away with the unbound method):

def just_foo_cols(self):
    """Get a list of column names containing the string 'foo'

    """
    return [x for x in self.columns if 'foo' in x]

Next we simply attach that method to the class we want to use it on:

pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class

And then we can use the method on an instance of the class, and delete the method when we're done:

df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method

Caveat for name-mangling

If you're using name-mangling (prefixing attributes with a double-underscore, which alters the name, and which I don't recommend) you'll have to name-mangle manually if you do this. Since I don't recommend name-mangling, I will not demonstrate it here.

Testing Example

How can we use this knowledge, for example, in testing?

Say we need to simulate a data retrieval call to an outside data source that results in an error, because we want to ensure correct behavior in such a case. We can monkey patch the data structure to ensure this behavior. (So using a similar method name as suggested by Daniel Roseman:)

import datasource

def get_data(self):
    '''monkey patch datasource.Structure with this to simulate error'''
    raise datasource.DataRetrievalError

datasource.Structure.get_data = get_data

And when we test it for behavior that relies on this method raising an error, if correctly implemented, we'll get that behavior in the test results.

Just doing the above will alter the Structure object for the life of the process, so you'll want to use setups and teardowns in your unittests to avoid doing that, e.g.:

def setUp(self):
    # retain a pointer to the actual real method:
    self.real_get_data = datasource.Structure.get_data
    # monkey patch it:
    datasource.Structure.get_data = get_data

def tearDown(self):
    # give the real method back to the Structure object:
    datasource.Structure.get_data = self.real_get_data

(While the above is fine, it would probably be a better idea to use the mock library to patch the code. mock's patch decorator would be less error prone than doing the above, which would require more lines of code and thus more opportunities to introduce errors. I have yet to review the code in mock but I imagine it uses monkey-patching in a similar way.)

MATLAB - multiple return values from a function?

Use the following in the function you will call and it will work just fine.

     [a b c] = yourfunction(optional)
     %your code
     a = 5;
     b = 7;
     c = 10;
     return
     end

This is a way to call the function both from another function and from the command terminal

     [aa bb cc] = yourfunction(optional);

The variables aa, bb and cc now hold the return variables.

/bin/sh: pushd: not found

A workaround for this would be to have a variable get the current working directory. Then you can cd out of it to do whatever, then when you need it, you can cd back in.

i.e.

oldpath=`pwd`
#do whatever your script does
...
...
...
# go back to the dir you wanted to pushd
cd $oldpath

How to store the hostname in a variable in a .bat file?

Just create a .bat file with the line

hostname

in it. That's it. Windows also supports the hostname command.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Look here.

Basically you have to do bind params:

$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)"; 

$this->db->query($sql, '__COUNTRY_NAME__');

But, like Mr.E said, use joins:

$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?"; 

$this->db->query($sql, '__COUNTRY_NAME__');

Turning multi-line string into single comma-separated

You can use grep:

grep -o "+\S\+" in.txt | tr '\n' ','

which finds the string starting with +, followed by any string \S\+, then convert new line characters into commas. This should be pretty quick for large files.

Postgresql tables exists, but getting "relation does not exist" when querying

I had to include double quotes with the table name.

db=> \d
                           List of relations
 Schema |                     Name                      | Type  | Owner 
--------+-----------------------------------------------+-------+-------
 public | COMMONDATA_NWCG_AGENCIES                      | table | dan
 ...

db=> \d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".

???

Double quotes:

db=> \d "COMMONDATA_NWCG_AGENCIES"
                         Table "public.COMMONDATA_NWCG_AGENCIES"
          Column          |            Type             | Collation | Nullable | Default 
--------------------------+-----------------------------+-----------+----------+---------
 ID                       | integer                     |           | not null | 
 ...

Lots and lots of double quotes:

db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR:  relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
                       ^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR:  column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
               ^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
 ID 
----
  1
(1 row)

This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:

DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";

CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...

npm throws error without sudo

Other answers are suggesting to change ownerships or permissions of system directories to a specific user. I highly disadvise from doing so, this can become very awkward and might mess up the entire system!

Here is a more generic and safer approach that supports multi-user as well.

Create a new group for node-users and add the required users to this group. Then set the ownership of node-dependant files/directories to this group.

# Create new group
sudo groupadd nodegrp 

# Add user to group (logname is a variable and gets replaced by the currently logged in user)
sudo usermod -a -G nodegrp `logname`

# Instant access to group without re-login
newgrp nodegrp

# Check group - nodegrp should be listed as well now
groups

# Change group of node_modules, node, npm to new group 
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

# (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)

Now you can easily install your modules as user

npm install -g generator-angular

Some modules (grunt, bower, yo etc.) will still need to be installed as root. This is because they create symlinks in /user/bin/.

Edit

3 years later I'd recommend to use Node Version Manager. It safes you a lot of time and trouble.

jQuery UI autocomplete with item and id

Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

    {"list":[
     {"value": 1, "label": "abc"},
     {"value": 2, "label": "def"},
     {"value": 3, "label": "ghi"}
    ]}

Then on the source portion of the autocomplete method:

    source: function(request, response) {
        $.getJSON("listing.php", {
            term: request.term
        }, function(data) {                     
            var array = data.error ? [] : $.map(data.list, function(m) {
                return {
                    label: m.label,
                    value: m.value
                };
            });
            response(array);
        });
    },
    select: function (event, ui) {
        $("#autocomplete_field").val(ui.item.label); // display the selected text
        $("#field_id").val(ui.item.value); // save selected id to hidden input
        return false;
    }

Hope this helps... all the best!

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

Converting string format to datetime in mm/dd/yyyy

You can change the format too by doing this

string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");

// this change the "/" for the "-"

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

How to hide code from cells in ipython notebook visualized with nbviewer?

With all the solutions above even though you're hiding the code, you'll still get the [<matplotlib.lines.Line2D at 0x128514278>] crap above your figure which you probably don't want.

If you actually want to get rid of the input rather than just hiding it, I think the cleanest solution is to save your figures to disk in hidden cells, and then just including the images in Markdown cells using e.g. ![Caption](figure1.png).

How to disable Compatibility View in IE

Another way to achieve this in Apache is by putting the following lines in .htaccess in the root folder of your website (or in Apache's config files).

BrowserMatch "MSIE" isIE
BrowserMatch "Trident" isIE
Header set X-UA-Compatible "IE=edge" env=isIE

This requires that you have the mod_headers and mod_setenvif modules enabled.

The extra HTTP header only gets sent to IE browsers, and none of the others.

How to match letters only using java regex, matches method?

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

Is it safe to store a JWT in localStorage with ReactJS?

Localstorage is designed to be accessible by javascript, so it doesn't provide any XSS protection. As mentioned in other answers, there is a bunch of possible ways to do an XSS attack, from which localstorage is not protected by default.

However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.

So cookies are a more secure choice for storing authentication data.

Angular 2 Dropdown Options Default Value

<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option value="{{workout.name}}" *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

If you are using form there should be name field inside select tag.

All you need to do is just add value to the option tag.

selectedWorkout value should be "back" , and its done.

How to avoid .pyc files?

In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.

In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont_write_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environment variable "PYTHONDONTWRITEBYTECODE"

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

difference between css height : 100% vs height : auto

A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto height will be the minimum height of necessary to contain .

How to Save Console.WriteLine Output to Text File

Try if this works:

FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

Python 2.7 getting user input and manipulating as string without quotations

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

Cordova - Error code 1 for command | Command failed for

I'm using Visual Studio 2015, and I've found that the first thing to do is look in the build output.

I found this error reported there:

Reading build config file: \build.json... SyntaxError: Unexpected token

The solution for that was to remove the bom from the build.json file

Then I hit a second problem - with this message in the build output:

FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':packageRelease'.

File 'C:\Users\Colin\etc' specified for property 'signingConfig.storeFile' is not a file.

Easily solved by putting the correct filename into the keystore property

Assign a login to a user created without login (SQL Server)

Through trial and error, it seems if the user was originally created "without login" then this query

select * from sys.database_principals

will show authentication_type = 0 (NONE).

Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:

alter user [TempUser] with login [TempLogin]

responds with the Remap Error "Msg 33016" shown in the question.

Also these users do not show up in classic (deprecating) SP report:

exec sp_change_users_login 'Report'

If anyone knows a way around this or how to change authentication_type, please comment.

"Untrusted App Developer" message when installing enterprise iOS Application

For iOS 13.6

Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Custom header to HttpClient request

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

How do I create a Bash alias?

MacOS Catalina and Above

Apple switched their default shell to zsh, so the config files include ~/.zshenv and ~/.zshrc. This is just like ~/.bashrc, but for zsh. Just edit the file and add what you need; it should be sourced every time you open a new terminal window:

nano ~/.zshenv alias py=python

Then do ctrl+x, y, then enter to save.

This file seems to be executed no matter what (login, non-login, or script), so seems better than the ~/.zshrc file.

High Sierra and earlier

The default shell is bash, and you can edit the file ~/.bash_profile and add aliases:

nano ~/.bash_profile alias py=python

Then ctrl+x, y, and enter to save. See this post for more on these configs. It's a little better to set it up with your alias in ~/.bashrc, then source ~/.bashrc from ~/.bash_profile. In ~/.bash_profile it would then look like:

source ~/.bashrc

How to fix Error: laravel.log could not be opened?

This solution is specific for laravel 5.5

You have to change permissions to a few folders: chmod -R -777 storage/logs chmod -R -777 storage/framework for the above folders 775 or 765 did not work for my project

chmod -R 775 bootstrap/cache 

Also the ownership of the project folder should be as follows (current user):(web server user)

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

What is and how to fix System.TypeInitializationException error?

If you have custom attributes in appsetting. move your

     <configSections> 
     </configSections>

tag to the first child in the <confuguration>.

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

How to set default value for HTML select?

You should define the attributes of option like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

How do I execute a string containing Python code in Python?

In the example a string is executed as code using the exec function.

import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
    x = x + 1
    return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void);

That is the correct way to say "no parameters" in C, and it also works in C++.

But:

void foo();

Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).

Variable argument list functions are inherently un-typesafe and should be avoided where possible.

Postgres integer arrays as parameters?

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ 
    DECLARE
           ids INT[];
    BEGIN
           ids = string_to_array($1,',');
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(:1)
    

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method('{1,2,3,4}')
    
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(ARRAY [1,2,3,4])
    

npm notice created a lockfile as package-lock.json. You should commit this file

Yes. You should add this file to your version control system, i.e. You should commit it.

This file is intended to be committed into source repositories

You can read more about what it is/what it does here:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

Rails: Why "sudo" command is not recognized?

That you are running Windows. Read:

http://en.wikipedia.org/wiki/Sudo

It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.

That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.

Line Break in XML formatting?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text.

Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Image, saved to sdcard, doesn't appear in Android's Gallery app

My answer to the original question and to anyone else that may have this problem:

I was having this same problem, images in my app that people saved to the SD card were not showing up in their Gallery immediately. After some searching I found this one line of code inserted after my 'save to sdcard' code that fixed the problem:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

How would I check a string for a certain letter in Python?

If you want a version that raises an error:

"string to search".index("needle") 

If you want a version that returns -1:

"string to search".find("needle") 

This is more efficient than the 'in' syntax

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

What is the difference between '/' and '//' when used for division?

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

What is the difference between Left, Right, Outer and Inner Joins?

There are three basic types of join:

  • INNER join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.
  • CROSS join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.
  • OUTER join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
    • LEFT means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match.
    • RIGHT means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match.
    • FULL means keep all records from both tables, and insert a NULL value in either table if there is no match.

Often you see will the OUTER keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.

Here is an example of when you might want to use each type:

  • INNER: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.
  • OUTER: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.
  • CROSS: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.

Check if one date is between two dates

Here is a Date Prototype method written in typescript:

Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
  if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
  return !minDate ? true : this.getTime() >= minDate.getTime()
    && !maxDate ? true : this.getTime() <= maxDate.getTime();
};

Remove shadow below actionbar

Try This it helped me without changing theme . Put Your AppBarLayout inside any layout.Hope this will help you

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


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:layout_height="?attr/actionBarSize"
       android:background="@color/white">
        <ImageView
            android:src="@drawable/go_grocery_logo"
            android:layout_width="108dp"
            android:layout_height="32dp" />
    </android.support.v7.widget.Toolbar>


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

Convert HashBytes to VarChar

Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0) instead of master.dbo.fn_varbintohexstr and then substringing the result.

In fact fn_varbintohexstr calls fn_varbintohexsubstring internally. The first argument of fn_varbintohexsubstring tells it to add 0xF as the prefix or not. fn_varbintohexstr calls fn_varbintohexsubstring with 1 as the first argument internaly.

Because you don't need 0xF, call fn_varbintohexsubstring directly.

isset in jQuery?

function el(id) {
  return document.getElementById(id);
}

if (el('one') || el('two') || el('three')) { 
  alert('yes');

} else if (el('four')) {
  alert('no');
}

Output single character in C

The easiest way to output a single character is to simply use the putchar function. After all, that's it's sole purpose and it cannot do anything else. It cannot be simpler than that.

Style input type file?

Here's a simple css only solution, that creates a consistent target area, and lets you style your faux elements however you like.

The basic idea is this:

  1. Have two "fake" elements (a text input/link) as siblings to your real file input. Absolutely position them so they're exactly on top of your target area.
  2. Wrap your file input with a div. Set overflow to hidden (so the file input doesn't spill out), and make it exactly the size that you want your target area to be.
  3. Set opacity to 0 on the file input so it's hidden but still clickable. Give it a large font size so the you can click on all portions of the target area.

Here's the jsfiddle: http://jsfiddle.net/gwwar/nFLKU/

<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    <a href="#" id="browse">Browse </a>
    <div id="wrapper">
        <input id="input" size="100" type="file" />
    </div>
</form>

Recommended way of making React component/div draggable

The answer by Jared Forsyth is horribly wrong and outdated. It follows a whole set of antipatterns such as usage of stopPropagation, initializing state from props, usage of jQuery, nested objects in state and has some odd dragging state field. If being rewritten, the solution will be the following, but it still forces virtual DOM reconciliation on every mouse move tick and is not very performant.

UPD. My answer was horribly wrong and outdated. Now the code alleviates issues of slow React component lifecycle by using native event handlers and style updates, uses transform as it doesn't lead to reflows, and throttles DOM changes through requestAnimationFrame. Now it's consistently 60 FPS for me in every browser I tried.

const throttle = (f) => {
    let token = null, lastArgs = null;
    const invoke = () => {
        f(...lastArgs);
        token = null;
    };
    const result = (...args) => {
        lastArgs = args;
        if (!token) {
            token = requestAnimationFrame(invoke);
        }
    };
    result.cancel = () => token && cancelAnimationFrame(token);
    return result;
};

class Draggable extends React.PureComponent {
    _relX = 0;
    _relY = 0;
    _ref = React.createRef();

    _onMouseDown = (event) => {
        if (event.button !== 0) {
            return;
        }
        const {scrollLeft, scrollTop, clientLeft, clientTop} = document.body;
        // Try to avoid calling `getBoundingClientRect` if you know the size
        // of the moving element from the beginning. It forces reflow and is
        // the laggiest part of the code right now. Luckily it's called only
        // once per click.
        const {left, top} = this._ref.current.getBoundingClientRect();
        this._relX = event.pageX - (left + scrollLeft - clientLeft);
        this._relY = event.pageY - (top + scrollTop - clientTop);
        document.addEventListener('mousemove', this._onMouseMove);
        document.addEventListener('mouseup', this._onMouseUp);
        event.preventDefault();
    };

    _onMouseUp = (event) => {
        document.removeEventListener('mousemove', this._onMouseMove);
        document.removeEventListener('mouseup', this._onMouseUp);
        event.preventDefault();
    };

    _onMouseMove = (event) => {
        this.props.onMove(
            event.pageX - this._relX,
            event.pageY - this._relY,
        );
        event.preventDefault();
    };

    _update = throttle(() => {
        const {x, y} = this.props;
        this._ref.current.style.transform = `translate(${x}px, ${y}px)`;
    });

    componentDidMount() {
        this._ref.current.addEventListener('mousedown', this._onMouseDown);
        this._update();
    }

    componentDidUpdate() {
        this._update();
    }

    componentWillUnmount() {
        this._ref.current.removeEventListener('mousedown', this._onMouseDown);
        this._update.cancel();
    }

    render() {
        return (
            <div className="draggable" ref={this._ref}>
                {this.props.children}
            </div>
        );
    }
}

class Test extends React.PureComponent {
    state = {
        x: 100,
        y: 200,
    };

    _move = (x, y) => this.setState({x, y});

    // you can implement grid snapping logic or whatever here
    /*
    _move = (x, y) => this.setState({
        x: ~~((x - 5) / 10) * 10 + 5,
        y: ~~((y - 5) / 10) * 10 + 5,
    });
    */

    render() {
        const {x, y} = this.state;
        return (
            <Draggable x={x} y={y} onMove={this._move}>
                Drag me
            </Draggable>
        );
    }
}

ReactDOM.render(
    <Test />,
    document.getElementById('container'),
);

and a bit of CSS

.draggable {
    /* just to size it to content */
    display: inline-block;
    /* opaque background is important for performance */
    background: white;
    /* avoid selecting text while dragging */
    user-select: none;
}

Example on JSFiddle.

Why can't I duplicate a slice with `copy()`?

If your slices were of the same size, it would work:

arr := []int{1, 2, 3}
tmp := []int{0, 0, 0}
i := copy(tmp, arr)
fmt.Println(i)
fmt.Println(tmp)
fmt.Println(arr)

Would give:

3
[1 2 3]
[1 2 3]

From "Go Slices: usage and internals":

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements)

The usual example is:

t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t

Understanding PIVOT function in T-SQL

FOR XML PATH might not work on Microsoft Azure Synapse Serve. A possible alternative, following @Taryn dynamic generated cols approach, same results is obtained by using STRING_AGG.

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)

SELECT @cols = STRING_AGG(QUOTENAME(c.phaseid),', ')
/*OPTIONAL: within group (order by cast(t1.[FLOW_SP_SLPM] as INT) asc)*/
FROM (SELECT phaseid FROM temp
GROUP BY phaseid) c

set @query = 'SELECT elementid,' + @cols + ' from 
             (
                select elementid,
                phaseid,
                effort
                from temp
            ) x
            PIVOT 
            (
                max(effort)
                for phaseid in (' + @cols + ')
            ) p '

execute(@query)

Clang vs GCC for my Linux Development project

EDIT:

The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.


Original:

For students, I would unconditionally recommend Clang.

The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.

On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.

Consider this simple snippet:

#include <string>
#include <iostream>

struct Student {
std::string surname;
std::string givenname;
}

std::ostream& operator<<(std::ostream& out, Student const& s) {
  return out << "{" << s.surname << ", " << s.givenname << "}";
}

int main() {
  Student me = { "Doe", "John" };
  std::cout << me << "\n";
}

You'll notice right away that the semi-colon is missing after the definition of the Student class, right :) ?

Well, gcc notices it too, after a fashion:

prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]

And Clang is not exactly starring here either, but still:

/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
     ^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
  typedef basic_ostream<char>           ostream;        ///< @isiosfwd
                                        ^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
            ^
            ;
2 errors generated.

I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.

How do I configure different environments in Angular.js?

To achieve that, I suggest you to use AngularJS Environment Plugin: https://www.npmjs.com/package/angular-environment

Here's an example:

angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
    // set the domains and variables for each environment 
    envServiceProvider.config({
        domains: {
            development: ['localhost', 'dev.local'],
            production: ['acme.com', 'acme.net', 'acme.org']
            // anotherStage: ['domain1', 'domain2'], 
            // anotherStage: ['domain1', 'domain2'] 
        },
        vars: {
            development: {
                apiUrl: '//localhost/api',
                staticUrl: '//localhost/static'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            },
            production: {
                apiUrl: '//api.acme.com/v2',
                staticUrl: '//static.acme.com'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            }
            // anotherStage: { 
            //  customVar: 'lorem', 
            //  customVar: 'ipsum' 
            // } 
        }
    });

    // run the environment check, so the comprobation is made 
    // before controllers and services are built 
    envServiceProvider.check();
});

And then, you can call the variables from your controllers such as this:

envService.read('apiUrl');

Hope it helps.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

Android: Rotate image in imageview by an angle

If you're supporting API 11 or higher, you can just use the following XML attribute:

android:rotation="90"

It might not display correctly in Android Studio xml preview, but it works as expected.

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

How do include paths work in Visual Studio?

This answer will be useful for those who use a non-standard IDE (i.e. Qt Creator).

There are at least two non-intrusive ways to pass additional include paths to Visual Studio's cl.exe via environment variables:

  • Set INCLUDE environment variable to ;-separated list of all include paths. It overrides all includes, inclusive standard library ones. Not recommended.
  • Set CL environment variable to the following value: /I C:\Lib\VulkanMemoryAllocator\src /I C:\Lib\gli /I C:\Lib\gli\external, where each argument of /I key is additional include path.

I successfully use the last one.

Reverse colormap in matplotlib

As a LinearSegmentedColormaps is based on a dictionary of red, green and blue, it's necessary to reverse each item:

import matplotlib.pyplot as plt
import matplotlib as mpl
def reverse_colourmap(cmap, name = 'my_cmap_r'):
    """
    In: 
    cmap, name 
    Out:
    my_cmap_r

    Explanation:
    t[0] goes from 0 to 1
    row i:   x  y0  y1 -> t[0] t[1] t[2]
                   /
                  /
    row i+1: x  y0  y1 -> t[n] t[1] t[2]

    so the inverse should do the same:
    row i+1: x  y1  y0 -> 1-t[0] t[2] t[1]
                   /
                  /
    row i:   x  y1  y0 -> 1-t[n] t[2] t[1]
    """        
    reverse = []
    k = []   

    for key in cmap._segmentdata:    
        k.append(key)
        channel = cmap._segmentdata[key]
        data = []

        for t in channel:                    
            data.append((1-t[0],t[2],t[1]))            
        reverse.append(sorted(data))    

    LinearL = dict(zip(k,reverse))
    my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL) 
    return my_cmap_r

See that it works:

my_cmap        
<matplotlib.colors.LinearSegmentedColormap at 0xd5a0518>

my_cmap_r = reverse_colourmap(my_cmap)

fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = my_cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = my_cmap_r, norm=norm, orientation='horizontal')

enter image description here

EDIT


I don't get the comment of user3445587. It works fine on the rainbow colormap:

cmap = mpl.cm.jet
cmap_r = reverse_colourmap(cmap)

fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = cmap_r, norm=norm, orientation='horizontal')

enter image description here

But it especially works nice for custom declared colormaps, as there is not a default _r for custom declared colormaps. Following example taken from http://matplotlib.org/examples/pylab_examples/custom_cmap.html:

cdict1 = {'red':   ((0.0, 0.0, 0.0),
                   (0.5, 0.0, 0.1),
                   (1.0, 1.0, 1.0)),

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 1.0),
                   (0.5, 0.1, 0.0),
                   (1.0, 0.0, 0.0))
         }

blue_red1 = mpl.colors.LinearSegmentedColormap('BlueRed1', cdict1)
blue_red1_r = reverse_colourmap(blue_red1)

fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])

norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = blue_red1, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = blue_red1_r, norm=norm, orientation='horizontal')

enter image description here

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

Could not open input file: composer.phar

First try this: dont use the php composer.phar [parameters] simply use composer [parameters] if this doesn't work for you than try the rest. Hope it helps.

Laravel blank white screen

I was also getting same error when I start first time on laravel + Ubuntu 14.04 I just right click on bootstrap and storage folder >>> properties >>>permission>> Others Access >>> change it to "Create and delete files" Change permission for enclosed files

Thank you

Convert a dataframe to a vector (by rows)

You can try as.vector(t(test)). Please note that, if you want to do it by columns you should use unlist(test).

Getting the absolute path of the executable, using C#?

The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

"Integer number too large" error message for 600851475143

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

How do I call a non-static method from a static method in C#?

You'll need to create an instance of the class and invoke the method on it.

public class Foo
{
    public void Data1()
    {
    }

    public static void Data2()
    {
         Foo foo = new Foo();
         foo.Data1();
    }
}

Spaces in URLs?

Spaces are simply replaced by "%20" like :

http://www.example.com/my%20beautiful%20page

Compare two folders which has many files inside contents

Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.

 -b              Ignores trailing blanks  (spaces  and  tabs)
                 and   treats  other  strings  of  blanks  as
                 equivalent.

 -i              Ignores the case of  letters.  For  example,
                 `A' will compare equal to `a'.
 -t              Expands <TAB> characters  in  output  lines.
                 Normal or -c output adds character(s) to the
                 front of each line that may adversely affect
                 the indentation of the original source lines
                 and  make  the  output  lines  difficult  to
                 interpret.  This  option  will  preserve the
                 original source's indentation.

 -w              Ignores all blanks (<SPACE> and <TAB>  char-
                 acters)  and  treats  all  other  strings of
                 blanks   as   equivalent.    For    example,
                 `if ( a == b )'   will   compare   equal  to
                 `if(a==b)'.

and there are many more.

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

How to center a navigation bar with CSS or HTML?

If you have your navigation <ul> with class #nav Then you need to put that <ul> item within a div container. Make your div container the 100% width. and set the text-align: element to center in the div container. Then in your <ul> set that class to have 3 particular elements: text-align:center; position: relative; and display: inline-block;

that should center it.

Replace all double quotes within String

Here's how

String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details);               // Hello \"world\"!

Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.


Using

details = details.replaceAll("\"","&quote;");

instead, results in

Hello &quote;world&quote;!

Difference between CR LF, LF and CR line break types?

CR - ASCII code 13

LF - ASCII code 10.

Theoretically CR returns cursor to the first position (on the left). LF feeds one line moving cursor one line down. This is how in old days you controled printers and text-mode monitors. These characters are usually used to mark end of lines in text files. Different operating systems used different conventions. As you pointed out Windows uses CR/LF combination while pre-OSX Macs use just CR and so on.

How do I update zsh to the latest version?

As far as I'm aware, you've got three options to install zsh on Mac OS X:

  • Pre-built binary. The only one I know of is the one that ships with OS X; this is probably what you're running now.
  • Use a package system (Ports, Homebrew).
  • Install from source. Last time I did this it wasn't too difficult (./configure, make, make install).

How do I alias commands in git?

You can set custom git aliases using git's config. Here's the syntax:

git config --global alias.<aliasName> "<git command>"

For example, if you need an alias to display a list of files which have merge conflicts, run:

git config --global alias.conflicts "diff --name-only --diff-filter=U"

Now you can use the above command only using "conflicts":

git conflicts
# same as running: git diff --name-only --diff-filter=U

setting global sql_mode in mysql

Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

MySQL restart.

Or you can also do

[mysqld]
port = 3306
SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";

MySQL restart.

Read and write a String from text file

I had to recode like this:

let path = NSBundle.mainBundle().pathForResource("Output_5", ofType: "xml")
let text = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding)
print(text)

How to programmatically set drawableLeft on Android button?

I did this:

 // Left, top, right, bottom drawables.
            Drawable[] drawables = button.getCompoundDrawables();
            // get left drawable.
            Drawable leftCompoundDrawable = drawables[0];
            // get new drawable.
            Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);
            // set image size (don't change the size values)
            img.setBounds(leftCompoundDrawable.getBounds());
            // set new drawable
            button.setCompoundDrawables(img, null, null, null);

How can I sharpen an image in OpenCV?

For clarity in this topic, a few points really should be made:

  1. Sharpening images is an ill-posed problem. In other words, blurring is a lossy operation, and going back from it is in general not possible.

  2. To sharpen single images, you need to somehow add constraints (assumptions) on what kind of image it is you want, and how it has become blurred. This is the area of natural image statistics. Approaches to do sharpening hold these statistics explicitly or implicitly in their algorithms (deep learning being the most implicitly coded ones). The common approach of up-weighting some of the levels of a DOG or Laplacian pyramid decomposition, which is the generalization of Brian Burns answer, assumes that a Gaussian blurring corrupted the image, and how the weighting is done is connected to assumptions on what was in the image to begin with.

  3. Other sources of information can render the problem sharpening well-posed. Common such sources of information is video of a moving object, or multi-view setting. Sharpening in that setting is usually called super-resolution (which is a very bad name for it, but it has stuck in academic circles). There has been super-resolution methods in OpenCV since a long time.... although they usually dont work that well for real problems last I checked them out. I expect deep learning has produced some wonderful results here as well. Maybe someone will post in remarks on whats worthwhile out there.

Skip Git commit hooks

For those very beginners who has spend few hours for this commit (with comment and no verify) with no further issue

git commit -m "Some comments" --no-verify

How to count certain elements in array?

_x000D_
_x000D_
var arrayCount = [1,2,3,2,5,6,2,8];_x000D_
var co = 0;_x000D_
function findElement(){_x000D_
    arrayCount.find(function(value, index) {_x000D_
      if(value == 2)_x000D_
        co++;_x000D_
    });_x000D_
    console.log( 'found' + ' ' + co + ' element with value 2');_x000D_
}
_x000D_
_x000D_
_x000D_

I would do something like that:

_x000D_
_x000D_
var arrayCount = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
function countarr(){_x000D_
  var dd = 0;_x000D_
  arrayCount.forEach( function(s){_x000D_
    dd++;_x000D_
  });_x000D_
_x000D_
  console.log(dd);_x000D_
}
_x000D_
_x000D_
_x000D_

Where is svn.exe in my machine?

Recent versions of the TortoiseSVN package can install a discrete svn.exe in addition to the one linked into the GUI binary. It is located in the same bin directory where the main program is installed. (If you have already installed TortoiseSVN, then rerun the installer, select Modify, and select command line tools for installation.)

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

Here are some variations on Sotirios Delimanolis' answer, which was pretty good to begin with (+1). Consider the following:

static <X, Y, Z> Map<X, Z> transform(Map<? extends X, ? extends Y> input,
                                     Function<Y, Z> function) {
    return input.keySet().stream()
        .collect(Collectors.toMap(Function.identity(),
                                  key -> function.apply(input.get(key))));
}

A couple points here. First is the use of wildcards in the generics; this makes the function somewhat more flexible. A wildcard would be necessary if, for example, you wanted the output map to have a key that's a superclass of the input map's key:

Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<CharSequence, Integer> output = transform(input, Integer::parseInt);

(There is also an example for the map's values, but it's really contrived, and I admit that having the bounded wildcard for Y only helps in edge cases.)

A second point is that instead of running the stream over the input map's entrySet, I ran it over the keySet. This makes the code a little cleaner, I think, at the cost of having to fetch values out of the map instead of from the map entry. Incidentally, I initially had key -> key as the first argument to toMap() and this failed with a type inference error for some reason. Changing it to (X key) -> key worked, as did Function.identity().

Still another variation is as follows:

static <X, Y, Z> Map<X, Z> transform1(Map<? extends X, ? extends Y> input,
                                      Function<Y, Z> function) {
    Map<X, Z> result = new HashMap<>();
    input.forEach((k, v) -> result.put(k, function.apply(v)));
    return result;
}

This uses Map.forEach() instead of streams. This is even simpler, I think, because it dispenses with the collectors, which are somewhat clumsy to use with maps. The reason is that Map.forEach() gives the key and value as separate parameters, whereas the stream has only one value -- and you have to choose whether to use the key or the map entry as that value. On the minus side, this lacks the rich, streamy goodness of the other approaches. :-)

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to find the last day of the month from date?

There is also the built in PHP function cal_days_in_month()?

"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

Switch statement equivalent in Windows batch file

Compact form for short commands (no 'echo'):

IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...

After ^ must be an immediate line end, no spaces.

How to take last four characters from a varchar?

For Oracle SQL, SUBSTR(column_name, -# of characters requested) will extract last three characters for a given query. e.g.

SELECT SUBSTR(description,-3) FROM student.course;

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

EnterKey to press button in VBA Userform

Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub

Could not resolve placeholder in string value

In my case I had the same issue on running from eclipse. Just did the following to resolve it: Right Click the Project --> Mavan --> Update Project.

And it worked!

CodeIgniter 404 Page Not Found, but why?

It happens cause of multiple reasons but the answer missing above there's the "className" while extending your controller.

Make sure your class name is the same as your controller name is your controllers. e.g., If your controller name is Settings.php, you must extend the controller like.

class Settings extends CI_Controller
{
// some actions like...
     public function __construct(){
     // and so and so...
     }
}

What does the colon (:) operator do?

How would you write this for-each loop a different way so as to not incorporate the ":"?

Assuming that list is a Collection instance ...

public String toString() {
   String cardString = "";
   for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
      PlayingCard c = it.next();
      cardString = cardString + c + "\n";
   }
}

I should add the pedantic point that : is not an operator in this context. An operator performs an operation in an expression, and the stuff inside the ( ... ) in a for statement is not an expression ... according to the JLS.

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

Relative frequencies / proportions with dplyr

Here is a general function implementing Henrik's solution on dplyr 0.7.1.

freq_table <- function(x, 
                       group_var, 
                       prop_var) {
  group_var <- enquo(group_var)
  prop_var  <- enquo(prop_var)
  x %>% 
    group_by(!!group_var, !!prop_var) %>% 
    summarise(n = n()) %>% 
    mutate(freq = n /sum(n)) %>% 
    ungroup
}

How to force C# .net app to run only one instance in Windows?

to force running only one instace of a program in .net (C#) use this code in program.cs file:

public static Process PriorProcess()
    // Returns a System.Diagnostics.Process pointing to
    // a pre-existing process with the same name as the
    // current one, if any; or null if the current process
    // is unique.
    {
        Process curr = Process.GetCurrentProcess();
        Process[] procs = Process.GetProcessesByName(curr.ProcessName);
        foreach (Process p in procs)
        {
            if ((p.Id != curr.Id) &&
                (p.MainModule.FileName == curr.MainModule.FileName))
                return p;
        }
        return null;
    }

and the folowing:

[STAThread]
    static void Main()
    {
        if (PriorProcess() != null)
        {

            MessageBox.Show("Another instance of the app is already running.");
            return;
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form());
    }

Android Studio - mergeDebugResources exception

You may have a corrupted .9.png in your drawables directory

How to remove numbers from a string?

This can be done without regex which is more efficient:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
    num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

HTTP GET Request in Node.js Express

Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

How to create EditText with cross(x) button at end of it?

Use

android:drawableRight="@android:drawable/ic_input_delete"