Programs & Examples On #Strdup

strdup() - what does it do in C?

No point repeating the other answers, but please note that strdup() can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

Insert multiple lines into a file after specified pattern using shell script

if you want to do that with a bash script, that's useful.

echo $password | echo 'net.ipv4.ping_group_range=0 2147483647' |  sudo -S tee -a /etc/sysctl.conf

How to get the input from the Tkinter Text Widget?

Here is how I did it with python 3.5.2:

from tkinter import *
root=Tk()
def retrieve_input():
    inputValue=textBox.get("1.0","end-1c")
    print(inputValue)

textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit", 
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()

mainloop()

with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.

Assembly Language - How to do Modulo?

If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren't known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that's less efficient than hard-coding just the steps necessary for one constant.)

Never use div for known powers of 2: it's much slower than and for remainder, or right-shift for divide. Look at C compiler output for examples of unsigned or signed division by powers of 2, e.g. on the Godbolt compiler explorer. If you know a runtime input is a power of 2, use lea eax, [esi-1] ; and eax, edi or something like that to do x & (y-1). Modulo 256 is even more efficient: movzx eax, cl has zero latency on recent Intel CPUs (mov-elimination), as long as the two registers are separate.


In the simple/general case: unknown value at runtime

The DIV instruction (and its counterpart IDIV for signed numbers) gives both the quotient and remainder. For unsigned, remainder and modulus are the same thing. For signed idiv, it gives you the remainder (not modulus) which can be negative:
e.g. -5 / 2 = -2 rem -1. x86 division semantics exactly match C99's % operator.

DIV r32 divides a 64-bit number in EDX:EAX by a 32-bit operand (in any register or memory) and stores the quotient in EAX and the remainder in EDX. It faults on overflow of the quotient.

Unsigned 32-bit example (works in any mode)

mov eax, 1234          ; dividend low half
mov edx, 0             ; dividend high half = 0.  prefer  xor edx,edx

mov ebx, 10            ; divisor can be any register or memory

div ebx       ; Divides 1234 by 10.
        ; EDX =   4 = 1234 % 10  remainder
        ; EAX = 123 = 1234 / 10  quotient

In 16-bit assembly you can do div bx to divide a 32-bit operand in DX:AX by BX. See Intel's Architectures Software Developer’s Manuals for more information.

Normally always use xor edx,edx before unsigned div to zero-extend EAX into EDX:EAX. This is how you do "normal" 32-bit / 32-bit => 32-bit division.

For signed division, use cdq before idiv to sign-extend EAX into EDX:EAX. See also Why should EDX be 0 before using the DIV instruction?. For other operand-sizes, use cbw (AL->AX), cwd (AX->DX:AX), cdq (EAX->EDX:EAX), or cqo (RAX->RDX:RAX) to set the top half to 0 or -1 according to the sign bit of the low half.

div / idiv are available in operand-sizes of 8, 16, 32, and (in 64-bit mode) 64-bit. 64-bit operand-size is much slower than 32-bit or smaller on current Intel CPUs, but AMD CPUs only care about the actual magnitude of the numbers, regardless of operand-size.

Note that 8-bit operand-size is special: the implicit inputs/outputs are in AH:AL (aka AX), not DL:AL. See 8086 assembly on DOSBox: Bug with idiv instruction? for an example.

Signed 64-bit division example (requires 64-bit mode)

   mov    rax,  0x8000000000000000   ; INT64_MIN = -9223372036854775808
   mov    ecx,  10           ; implicit zero-extension is fine for positive numbers

   cqo                       ; sign-extend into RDX, in this case = -1 = 0xFF...FF
   idiv   rcx
       ; quotient  = RAX = -922337203685477580 = 0xf333333333333334
       ; remainder = RDX = -8                  = 0xfffffffffffffff8

Limitations / common mistakes

div dword 10 is not encodeable into machine code (so your assembler will report an error about invalid operands).

Unlike with mul/imul (where you should normally use faster 2-operand imul r32, r/m32 or 3-operand imul r32, r/m32, imm8/32 instead that don't waste time writing a high-half result), there is no newer opcode for division by an immediate, or 32-bit/32-bit => 32-bit division or remainder without the high-half dividend input.

Division is so slow and (hopefully) rare that they didn't bother to add a way to let you avoid EAX and EDX, or to use an immediate directly.


div and idiv will fault if the quotient doesn't fit into one register (AL / AX / EAX / RAX, the same width as the dividend). This includes division by zero, but will also happen with a non-zero EDX and a smaller divisor. This is why C compilers just zero-extend or sign-extend instead of splitting up a 32-bit value into DX:AX.

And also why INT_MIN / -1 is C undefined behaviour: it overflows the signed quotient on 2's complement systems like x86. See Why does integer division by -1 (negative one) result in FPE? for an example of x86 vs. ARM. x86 idiv does indeed fault in this case.

The x86 exception is #DE - divide exception. On Unix/Linux systems, the kernel delivers a SIGFPE arithmetic exception signal to processes that cause a #DE exception. (On which platforms does integer divide by zero trigger a floating point exception?)

For div, using a dividend with high_half < divisor is safe. e.g. 0x11:23 / 0x12 is less than 0xff so it fits in an 8-bit quotient.

Extended-precision division of a huge number by a small number can be implemented by using the remainder from one chunk as the high-half dividend (EDX) for the next chunk. This is probably why they chose remainder=EDX quotient=EAX instead of the other way around.

error: passing xxx as 'this' argument of xxx discards qualifiers

Member functions that do not modify the class instance should be declared as const:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

Anytime you see "discards qualifiers", it's talking about const or volatile.

jQuery Ajax POST example with PHP

Pure JS

In pure JS it will be much simpler

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

_x000D_
_x000D_
foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}
_x000D_
<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Git:nothing added to commit but untracked files present

Follow all the steps.

Step 1: initialize git

$ git init

Step 2: Check files are exist or not.

$git ls

Step 3 : Add the file

$git add filename

Step 4: Add comment to show

$git commit -m "your comment"

Step 5: Link to your repository

$git remote add origin  "copy repository link  and paste here"

Step 6: Push on Git

$ git push -u origin master

How do I run a program from command prompt as a different user and as an admin

You can use psexec.exe from Microsoft Sysinternals Suite https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite

Example:

c:\somedir\psexec.exe -u domain\user -p password cmd.exe

Bootstrap: How do I identify the Bootstrap version?

To check what version you currently have, you can use -v for the command line/console terminal.

bootstrap -v

https://www.npmjs.com/package/bootstrap-cli

Error Installing Homebrew - Brew Command Not Found

This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.

Managing jQuery plugin dependency in webpack

You've mixed different approaches how to include legacy vendor modules. This is how I'd tackle it:

1. Prefer unminified CommonJS/AMD over dist

Most modules link the dist version in the main field of their package.json. While this is useful for most developers, for webpack it is better to alias the src version because this way webpack is able to optimize dependencies better (e.g. when using the DedupePlugin).

// webpack.config.js

module.exports = {
    ...
    resolve: {
        alias: {
            jquery: "jquery/src/jquery"
        }
    }
};

However, in most cases the dist version works just fine as well.


2. Use the ProvidePlugin to inject implicit globals

Most legacy modules rely on the presence of specific globals, like jQuery plugins do on $ or jQuery. In this scenario you can configure webpack, to prepend var $ = require("jquery") everytime it encounters the global $ identifier.

var webpack = require("webpack");

    ...

    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]

3. Use the imports-loader to configure this

Some legacy modules rely on this being the window object. This becomes a problem when the module is executed in a CommonJS context where this equals module.exports. In this case you can override this with the imports-loader.

Run npm i imports-loader --save-dev and then

module: {
    loaders: [
        {
            test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
            loader: "imports-loader?this=>window"
        }
    ]
}

The imports-loader can also be used to manually inject variables of all kinds. But most of the time the ProvidePlugin is more useful when it comes to implicit globals.


4. Use the imports-loader to disable AMD

There are modules that support different module styles, like AMD, CommonJS and legacy. However, most of the time they first check for define and then use some quirky code to export properties. In these cases, it could help to force the CommonJS path by setting define = false.

module: {
    loaders: [
        {
            test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
            loader: "imports-loader?define=>false"
        }
    ]
}

5. Use the script-loader to globally import scripts

If you don't care about global variables and just want legacy scripts to work, you can also use the script-loader. It executes the module in a global context, just as if you had included them via the <script> tag.


6. Use noParse to include large dists

When there is no AMD/CommonJS version of the module and you want to include the dist, you can flag this module as noParse. Then webpack will just include the module without parsing it, which can be used to improve the build time. This means that any feature requiring the AST, like the ProvidePlugin, will not work.

module: {
    noParse: [
        /[\/\\]node_modules[\/\\]angular[\/\\]angular\.js$/
    ]
}

Multiple GitHub Accounts & SSH Config

In my case none of the solutions above solved my issue, but ssh-agent does. Basically, I did the following:

  1. Generate key pair using ssh-keygen shown below. It will generate a key pair (in this example .\keyfile and .\keyfile.pub)

    ssh-keygen -t rsa -b 4096 -C "yourname@yourdomain" -f keyfile

  2. Upload keyfile.pub to the git provider

  3. Start ssh-agent on your machine (you can check with ps -ef | grep ssh-agent to see if it is running already)
  4. Run ssh-add .\keyfile to add credentials
  5. Now you can run git clone git@provider:username/project.git

json_encode() escaping forward slashes

Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script> tags it's necessary as a </script> anywhere - even inside a string - will end the script tag.

Depending on where the JSON is used it's not necessary, but it can be safely ignored.

Is there a simple way to remove unused dependencies from a maven pom.xml?

I had similar kind of problem and decided to write a script that removes dependencies for me. Using that I got over half of the dependencies away rather easily.

http://samulisiivonen.blogspot.com/2012/01/cleanin-up-maven-dependencies.html

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).

An example of a FIRST/FIRST conflict:

S -> Xb | Yc
X -> a 
Y -> a 

By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.

An example of a FIRST/FOLLOW conflict:

S -> AB 
A -> fe | epsilon 
B -> fg 

By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).

Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.

How to check if a DateTime field is not null or empty?

If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:

DateTime dat = new DateTime();

 if (dat==DateTime.MinValue)
 {
     //unassigned
 }

If the DateTime is nullable, well that's a different story:

 DateTime? dat = null;

 if (!dat.HasValue)
 {
     //unassigned
 }

Windows Forms - Enter keypress activates submit button?

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.

Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

Can I update a component's props in React.js?

Much has changed with hooks, e.g. componentWillReceiveProps turned into useEffect+useRef (as shown in this other SO answer), but Props are still Read-Only, so only the caller method should update it.

Find rows that have the same value on a column in MySQL

I know this is a very old question but this is more for someone else who might have the same problem and I think this is more accurate to what was wanted.

SELECT * FROM member WHERE email = (Select email From member Where login_id = [email protected]) 

This will return all records that have [email protected] as a login_id value.

What is the best way to get the count/length/size of an iterator?

for Java 8 you could use,

public static int getIteratorSize(Iterator iterator){
        AtomicInteger count = new AtomicInteger(0);
        iterator.forEachRemaining(element -> {
            count.incrementAndGet();
        });
        return count.get();
    }

Getting a directory name from a filename

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();

Experimental decorators warning in TypeScript compilation

I get this warning displayed in vscode when creating a new Angular service with the

@Injectable({
  providedIn: 'root'
})

syntax (rather than providing the service in app.module.ts).

The warning persists until I reference the new service somewhere in the project. Once the service gets used the warning goes away. No typescript configuration or vscode settings changes necessary.

IPython/Jupyter Problems saving notebook as PDF

To convert notebooks to PDF you first need to have nbconvert installed.

pip install nbconvert
# OR
conda install nbconvert

Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:

sudo apt-get install pandoc

After that you need to have XeTex installed on your machine:

You can now navigate to the folder that holds your IPython Notebook and run the following command:

jupyter nbconvert --to pdf MyNotebook.ipynb

for further reference, please check out this link.

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

Make code in LaTeX look *nice*

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

Rename a column in MySQL

Rename MySQL Column with ALTER TABLE Command

ALTER TABLE is an essential command used to change the structure of a MySQL table. You can use it to add or delete columns, change the type of data within the columns, and even rename entire databases. The function that concerns us the most is how to utilize ALTER TABLE to rename a column.

Clauses give us additional control over the renaming process. The RENAME COLUMN and CHANGE clause both allow for the names of existing columns to be altered. The difference is that the CHANGE clause can also be used to alter the data types of a column. The commands are straightforward, and you may use the clause that fits your requirements best.

How to Use the RENAME COLUMN Clause (MySQL 8.0)

The simplest way to rename a column is to use the ALTER TABLE command with the RENAME COLUMN clause. This clause is available since MySQL version 8.0.

Let’s illustrate its simple syntax. To change a column name, enter the following statement in your MySQL shell:

ALTER TABLE your_table_name RENAME COLUMN original_column_name TO new_column_name;

Exchange the your_table_name, original_column_name, and new_column_name with your table and column names. Keep in mind that you cannot rename a column to a name that already exists in the table.

Note: The word COLUMN is obligatory for the ALTER TABLE RENAME COLUMN command. ALTER TABLE RENAME is the existing syntax to rename the entire table.

The RENAME COLUMN clause can only be used to rename a column. If you need additional functions, such as changing the data definition, or position of a column, you need to use the CHANGE clause instead.

Rename MySQL Column with CHANGE Clause

The CHANGE clause offers important additions to the renaming process. It can be used to rename a column and change the data type of that column with the same command.

Enter the following command in your MySQL client shell to change the name of the column and its definition:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name data_type;

The data_type element is mandatory, even if you want to keep the existing datatype.

Use additional options to further manipulate table columns. The CHANGE also allows you to place the column in a different position in the table by using the optional FIRST | AFTER column_name clause. For example:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name y_data_type AFTER column_x;

You have successfully changed the name of the column, changed the data type to y_data_type, and positioned the column after column_x.

Using Python's os.path, how do I go up one directory?

Of course: simply use os.chdir(..).

When to use static methods

Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:

A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.

A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.

Chrome ignores autocomplete="off"

UPDATE

It seems now Chrome ignores the style="display: none;" or style="visibility: hidden; attributes.

You can change it to something like:

<input style="opacity: 0;position: absolute;">
<input type="password" style="opacity: 0;position: absolute;">

In my experience, Chrome only autocompletes the first <input type="password"> and the previous <input>. So I've added:

<input style="display:none">
<input type="password" style="display:none">

To the top of the <form> and the case was resolved.

Good examples using java.util.logging

SLF4J is a better logging facade than Apache Commons Logging (ACL). It has bridges to other logging frameworks, making direct calls to ACL, Log4J, or Java Util Logging go through SLF4J, so that you can direct all output to one log file if you wish, with just one log configuration file. Why would your application use multiple logging frameworks? Because 3rd-party libraries you use, especially older ones, probably do.

SLF4J supports various logging implementations. It can output everything to standard-out, use Log4J, or Logback (recommended over Log4J).

http://www.slf4j.org/

http://logback.qos.ch/

Count immediate child div elements using jQuery

$("div", "#superpics").size();

"Operation must use an updateable query" error in MS Access

To update records, you need to write changes to .mdb file on disk. If your web/shared application can't write to disk, you can't update existing or add new records. So, enable read/write access in database folder or move database to other folder where your application has write permission....for more detail please check:

http://www.beansoftware.com/ASP.NET-FAQ/Operation-Must-Use-An-Updateable-Query.aspx

How to log Apache CXF Soap Request and Soap Response using Log4j?

Procedure for global setting of client/server logging of SOAP/REST requests/ responses with log4j logger. This way you set up logging for the whole application without having to change the code, war, jar files, etc.

  1. install file cxf-rt-features-logging-X.Y.Z.jar to your CLASS_PATH

  2. create file (path for example: /opt/cxf/cxf-logging.xml):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <cxf:bus>
     <cxf:features>
     <bean class="org.apache.cxf.ext.logging.LoggingFeature">
     <property name="prettyLogging" value="true"/>
     </bean>
     </cxf:features>
     </cxf:bus>
     </beans>
    
  3. set logging for org.apache.cxf (log4j 1.x) log4j.logger.org.apache.cxf=INFO,YOUR_APPENDER

  4. set these properties on java start-up

java ... -Dcxf.config.file.url=file:///opt/cxf/cxf-logging.xml -Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true -Dcom.sun.xml.internal.ws.transport.http.HttpAdapter.dump=true ...

I don't know why, but it is necessary to set variables as well com.sun.xml.*

How can I find where I will be redirected using cURL?

To make cURL follow a redirect, use:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Erm... I don't think you're actually executing the curl... Try:

curl_exec($ch);

...after setting the options, and before the curl_getinfo() call.

EDIT: If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
}

Uncaught ReferenceError: $ is not defined

There might be two issues:

1) The JQuery might not have got loaded properly. You could test it using Chrome. Key in $ or jQuery to check if it is loaded properly. Chrome Console

2) This is based on my experience in some JQuery.js which would have got bundled with other JS libraries, where $ will not be supported and you are forced to use jQuery instead of $ Check out for the below line in the js file that you have loaded in your project.

window.jQuery = window.$ = jQuery;

I see that by using http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js didn't work for me but I used http://code.jquery.com/jquery-1.7.2.min.js

Below is the only part in your code that I edited and it started working fine for me.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

Setting Curl's Timeout in PHP

If you are using PHP as a fastCGI application then make sure you check the fastCGI timeout settings. See: PHP curl put 500 error

How can I mix LaTeX in with Markdown?

I'll answer your question with a counter-question...

What do you think of Org-mode? It's not as pure as Markdown, but it is Markdown-like, and I find it as easy to work with, and it allows embedding of Latex. Cf. http://www.gnu.org/software/emacs/manual/html_node/org/Embedded-LaTeX.html

Postscript

In case you haven't looked at org-mode, it has one great strength as a general purpose "natural markup language" over Markdown, namely its treatment of tables. The source:

| 1 | 0 | 0 |
| -1 | 1 | 0 |
| -1 | -1 | 1 |

represents just what you think it will...

And the Latex is rendered in pieces using tex-mode's preview-latex.

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

OpenCV HSV range is: H: 0 to 179 S: 0 to 255 V: 0 to 255

On Gimp (or other photo manipulation sw) Hue range from 0 to 360, since opencv put color info in a single byte, the maximum number value in a single byte is 255 therefore openCV Hue values are equivalent to Hue values from gimp divided by 2.

I found when trying to do object detection based on HSV color space that a range of 5 (opencv range) was sufficient to filter out a specific color. I would advise you to use an HSV color palate to figure out the range that works best for your application.

HSV color palate with color detection in HSV space

Select query to get data from SQL Server

You should use ExecuteScalar() (which returns the first row first column) instead of ExecuteNonQuery() (which returns the no. of rows affected).

You should refer differences between executescalar and executenonquery for more details.

Hope it helps!

Rollback transaction after @Test

You need to run your test with a Spring context and a transaction manager, e.g.,

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"/your-applicationContext.xml"})
@TransactionConfiguration(transactionManager="txMgr")
public class StudentSystemTest {

     @Test
     public void testTransactionalService() {
         // test transactional service
     }

     @Test
     @Transactional
     public void testNonTransactionalService() {
         // test non-transactional service
     }
}

See chapter 3.5.8. Transaction Management of the Spring reference for further details.

Rename a dictionary key

In Python 3.6 (onwards?) I would go for the following one-liner

test = {'a': 1, 'old': 2, 'c': 3}
old_k = 'old'
new_k = 'new'
new_v = 4  # optional

print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))

which produces

{'a': 1, 'new': 4, 'c': 3}

May be worth noting that without the print statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...

.htaccess or .htpasswd equivalent on IIS?

This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx

I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Access to the path denied error in C#

If your problem persist with all those answers, try to change the file attribute to:

File.SetAttributes(yourfile, FileAttributes.Normal);

How to run VBScript from command line without Cscript/Wscript

When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by

assoc | grep -i vbs
.vbs=VBSFile

ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.

As

cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]

Options:
 //B         Batch mode: Suppresses script errors and prompts from displaying
 //D         Enable Active Debugging
 //E:engine  Use engine for executing script
 //H:CScript Changes the default script host to CScript.exe
 //H:WScript Changes the default script host to WScript.exe (default)
 //I         Interactive mode (default, opposite of //B)
 //Job:xxxx  Execute a WSF job
 //Logo      Display logo (default)
 //Nologo    Prevent logo display: No banner will be shown at execution time
 //S         Save current command line options for this user
 //T:nn      Time out in seconds:  Maximum time a script is permitted to run
 //X         Execute script in debugger
 //U         Use Unicode for redirected I/O from the console

shows, you can use //E and //S to permanently switch your default host to cscript.exe.

If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable

set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1

contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.

Update wrt comment:

If you 'don't want to specify the full path of my vbscript everytime' you may:

  1. put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
  2. put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS

In both cases I would type out the extension to avoid (nasty) surprises.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

Where find WTP:

Mouse down on < plugin > in pom.xml and 'Discover new m2e connectors'.

I installed them all what are default checked and it works.

Find object by id in an array of JavaScript objects

myArray.filter(function(a){ return a.id == some_id_you_want })[0]

Using intents to pass data between activities

Try this from your AndroidTabRestaurantDescSearchListView activity

Intent intent  = new Intent(this,RatingDescriptionSearchActivity.class );
intent.putExtras( getIntent().getExtras() );
startActivity( intent );  

And then from RatingDescriptionSearchActivity activity just call

getIntent().getStringExtra("key")

Unable to connect to any of the specified mysql hosts. C# MySQL

I am running mysql on a computer on a local network. MySQL Workbench could connect to that server, but not my c# code. I solved my issue by disconnecting from a vpn client that was running.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I wrote a blog entry about this, as I encountered this maddening problem, and finally yanked my system back into working order.

These are the things to check, in this order:

  1. Check your properties options in your linker settings at: Properties > Configuration Properties > Linker > Advanced > Target Machine. Select MachineX64 if you are targeting a 64 bit build, or MachineX86 if you are making a 32 bit build.

  2. Select Build > Configuration Manager from the main menu in visual studio. Make sure your project has the correct platform specified. It is possible for the IDE to be set to build x64 but an individual project in the solution can be set to target win32. So yeah, visual studio leaves a lot of rope to hang yourself, but that's life.

  3. Check your library files that they really are of the type of platform are targeting. This can be used by using dumpbin.exe which is in your visual studio VC\bin directory. use the -headers option to dump all your functions. Look for the machine entry for each function. it should include x64 if it's a 64 bit build.

  4. In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown. Make sure that the first entry is: $(VCInstallDir)\bin\x86_amd64 followed by $(VCInstallDir)\bin.

Once I did step 4 everything worked again for me. The thing was I was encountering this problem on all my projects where I wanted to compile towards a 64 bit target.

How to dynamically create a class?

You can look at using dynamic modules and classes that can do the job. The only disadvantage is that it remains loaded in the app domain. But with the version of .NET framework being used, that could change. .NET 4.0 supports collectible dynamic assemblies and hence you can recreate the classes/types dynamically.

How to resolve "Server Error in '/' Application" error?

The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.

Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application

Convert integers to strings to create output filenames at run time

For a shorten version. If all the indices are smaller than 10, then use the following:

do i=0,9
   fid=100+i
   fname='OUTPUT'//NCHAR(i+48) //'.txt'
   open(fid, file=fname)
   !....
end do

For a general version:

character(len=5) :: charI
do i = 0,100
   fid = 100 + i
   write(charI,"(A)"), i
   fname ='OUTPUT' // trim(charI) // '.txt'
   open(fid, file=fname)
end do

That's all.

How do I escape double and single quotes in sed?

Aside: sed expressions containing BASH variables need to be double (")-quoted for the variable to be interpreted correctly.

If you also double-quote your $BASH variable (recommended practice)

... then you can escape the variable double quotes as shown:

sed -i "s/foo/bar ""$VARIABLE""/g" <file>

I.e., replace the $VARIABLE-associated " with "".

(Simply -escaping "$VAR" as \"$VAR\" results in a "-quoted output string.)


Examples

$ VAR='apples and bananas'
$ echo $VAR
apples and bananas

$ echo "$VAR"
apples and bananas

$ printf 'I like %s!\n' $VAR
I like apples!
I like and!
I like bananas!

$ printf 'I like %s!\n' "$VAR"
I like apples and bananas!

Here, $VAR is "-quoted before piping to sed (sed is either '- or "-quoted):

$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!

$ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g'
I like apples and bananas!

$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!

$ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g'
I like apples and bananas!

$ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g"
I like cherries!

$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!

Compare that to:

$ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g"
I like apples!
I like and!
I like bananas!


$ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g"
I like apples!
I like and!
I like bananas!

... and so on ...

Conclusion

My recommendation, as standard practice, is to

  • "-quote BASH variables ("$VAR")
  • "-quote, again, those variables (""$VAR"") if they are used in a sed expression (which itself must be "-quoted, not '-quoted)
$ VAR='apples and bananas'

$ echo "$VAR"
apples and bananas

$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

JavaScript pattern for multiple constructors

I believe there are two answers. One using 'pure' Javascript with IIFE function to hide its auxiliary construction functions. And the other using a NodeJS module to also hide its auxiliary construction functions.

I will show only the example with a NodeJS module.

Class Vector2d.js:



/*

    Implement a class of type Vetor2d with three types of constructors.

*/

// If a constructor function is successfully executed,
// must have its value changed to 'true'.let global_wasExecuted = false;  
global_wasExecuted = false;   

//Tests whether number_value is a numeric type
function isNumber(number_value) {
    
    let hasError = !(typeof number_value === 'number') || !isFinite(number_value);

    if (hasError === false){
        hasError = isNaN(number_value);
    }

    return !hasError;
}

// Object with 'x' and 'y' properties associated with its values.
function vector(x,y){
    return {'x': x, 'y': y};
}

//constructor in case x and y are 'undefined'
function new_vector_zero(x, y){

    if (x === undefined && y === undefined){
        global_wasExecuted = true;
        return new vector(0,0);
    }
}

//constructor in case x and y are numbers
function new_vector_numbers(x, y){

    let x_isNumber = isNumber(x);
    let y_isNumber = isNumber(y);

    if (x_isNumber && y_isNumber){
        global_wasExecuted = true;
        return new vector(x,y);
    }
}

//constructor in case x is an object and y is any
//thing (he is ignored!)
function new_vector_object(x, y){

    let x_ehObject = typeof x === 'object';
    //ignore y type

    if (x_ehObject){

        //assigns the object only for clarity of code
        let x_object = x;

        //tests whether x_object has the properties 'x' and 'y'
        if ('x' in x_object && 'y' in x_object){

            global_wasExecuted = true;

            /*
            we only know that x_object has the properties 'x' and 'y',
            now we will test if the property values ??are valid,
            calling the class constructor again.            
            */
            return new Vector2d(x_object.x, x_object.y);
        }

    }
}


//Function that returns an array of constructor functions
function constructors(){
    let c = [];
    c.push(new_vector_zero);
    c.push(new_vector_numbers);
    c.push(new_vector_object);

    /*
        Your imagination is the limit!
        Create as many construction functions as you want.    
    */

    return c;
}

class Vector2d {

    constructor(x, y){

        //returns an array of constructor functions
        let my_constructors = constructors(); 

        global_wasExecuted = false;

        //variable for the return of the 'vector' function
        let new_vector;     

        //traverses the array executing its corresponding constructor function
        for (let index = 0; index < my_constructors.length; index++) {

            //execute a function added by the 'constructors' function
            new_vector = my_constructors[index](x,y);
            
            if (global_wasExecuted) {
            
                this.x = new_vector.x;
                this.y = new_vector.y;

                break; 
            };
        };
    }

    toString(){
        return `(x: ${this.x}, y: ${this.y})`;
    }

}

//Only the 'Vector2d' class will be visible externally
module.exports = Vector2d;  

The useVector2d.js file uses the Vector2d.js module:

const Vector = require('./Vector2d');

let v1 = new Vector({x: 2, y: 3});
console.log(`v1 = ${v1.toString()}`);

let v2 = new Vector(1, 5.2);
console.log(`v2 = ${v2.toString()}`);

let v3 = new Vector();
console.log(`v3 = ${v3.toString()}`);

Terminal output:

v1 = (x: 2, y: 3)
v2 = (x: 1, y: 5.2)
v3 = (x: 0, y: 0)

With this we avoid dirty code (many if's and switch's spread throughout the code), difficult to maintain and test. Each building function knows which conditions to test. Increasing and / or decreasing your building functions is now simple.

How do you declare an interface in C++?

To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Parent
{
    public:
        virtual ~Parent();
};

class Child : public Parent, public IDemo
{
    public:
        virtual void OverrideMe()
        {
            //do stuff
        }
};

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.

Parsing CSV files in C#, with header

Here is my KISS implementation...

using System;
using System.Collections.Generic;
using System.Text;

class CsvParser
{
    public static List<string> Parse(string line)
    {
        const char escapeChar = '"';
        const char splitChar = ',';
        bool inEscape = false;
        bool priorEscape = false;

        List<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < line.Length; i++)
        {
            char c = line[i];
            switch (c)
            {
                case escapeChar:
                    if (!inEscape)
                        inEscape = true;
                    else
                    {
                        if (!priorEscape)
                        {
                            if (i + 1 < line.Length && line[i + 1] == escapeChar)
                                priorEscape = true;
                            else
                                inEscape = false;
                        }
                        else
                        {
                            sb.Append(c);
                            priorEscape = false;
                        }
                    }
                    break;
                case splitChar:
                    if (inEscape) //if in escape
                        sb.Append(c);
                    else
                    {
                        result.Add(sb.ToString());
                        sb.Length = 0;
                    }
                    break;
                default:
                    sb.Append(c);
                    break;
            }
        }

        if (sb.Length > 0)
            result.Add(sb.ToString());

        return result;
    }

}

System has not been booted with systemd as init system (PID 1). Can't operate

You can simply run sudo service docker start which will start running your docker server. You can check if you have the docker server by running service --status-all, you should see docker listed.

How to customize listview using baseadapter

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

custom.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="255dp"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Video1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#339966"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="video1"
                    android:textColor="#606060" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

main.java:

package com.example.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {

    ListView l1;
    String[] t1={"video1","video2"};
    String[] d1={"lesson1","lesson2"};
    int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1=(ListView)findViewById(R.id.list);
        l1.setAdapter(new dataListAdapter(t1,d1,i1));
    }

    class dataListAdapter extends BaseAdapter {
        String[] Title, Detail;
        int[] imge;

        dataListAdapter() {
            Title = null;
            Detail = null;
            imge=null;
        }

        public dataListAdapter(String[] text, String[] text1,int[] text3) {
            Title = text;
            Detail = text1;
            imge = text3;

        }

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

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

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

        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = getLayoutInflater();
            View row;
            row = inflater.inflate(R.layout.custom, parent, false);
            TextView title, detail;
            ImageView i1;
            title = (TextView) row.findViewById(R.id.title);
            detail = (TextView) row.findViewById(R.id.detail);
            i1=(ImageView)row.findViewById(R.id.img);
            title.setText(Title[position]);
            detail.setText(Detail[position]);
            i1.setImageResource(imge[position]);

            return (row);
        }
    }
}

Try this.

Get only the date in timestamp in mysql

$date= new DateTime($row['your_date']) ;  
echo $date->format('Y-m-d');

Is there a method for String conversion to Title Case?

I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.

public static String toTitleCase(String input) {
    input = input.toLowerCase();
    char c =  input.charAt(0);
    String s = new String("" + c);
    String f = s.toUpperCase();
    return f + input.substring(1);
}

How do I resolve ClassNotFoundException?

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this: enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command: enter image description here

NOTE: You have to execute the above java command no matter what your current location is. But this is not the case for javac. For compiling you can even directly go into the directory where you have your .java files and directly execute javac ClassName.java.

How to set base url for rest in spring boot?

I found a clean solution, which affects only rest controllers.

@SpringBootApplication
public class WebApp extends SpringBootServletInitializer {

    @Autowired
    private ApplicationContext context;

    @Bean
    public ServletRegistrationBean restApi() {
        XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
        applicationContext.setParent(context);
        applicationContext.setConfigLocation("classpath:/META-INF/rest.xml");

        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        dispatcherServlet.setApplicationContext(applicationContext);

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/rest/*");
        servletRegistrationBean.setName("restApi");

        return servletRegistrationBean;
    }

    static public void main(String[] args) throws Exception {
        SpringApplication.run(WebApp.class,args);
    }
}

Spring boot will register two dispatcher servlets - default dispatcherServlet for controllers, and restApi dispatcher for @RestControllers defined in rest.xml:

2016-06-07 09:06:16.205  INFO 17270 --- [           main] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'restApi' to [/rest/*]
2016-06-07 09:06:16.206  INFO 17270 --- [           main] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]

The example rest.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="org.example.web.rest"/>
    <mvc:annotation-driven/>

    <!-- Configure to plugin JSON as request and response in method handler -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
</beans>

But, you're not limited to:

  • use XmlWebApplicationContext, you may use any else context type available, ie. AnnotationConfigWebApplicationContext, GenericWebApplicationContext, GroovyWebApplicationContext, ...
  • define jsonMessageConverter, messageConverters beans in rest context, they may be defined in parent context

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

Renew Provisioning Profile

In addition to the other solutions I needed to edit the code signing on the main project and the Target file to get the app building to the device again after an expired provisioning profile.

::Delete the old expired profiles

::Add the new profile with the Organizer

::Clean All Targets

::Get Info -> Code Signing on both the main project and the Target

::Build and Run

Paritition array into N chunks with Numpy

Just some examples on usage of array_split, split, hsplit and vsplit:

n [9]: a = np.random.randint(0,10,[4,4])

In [10]: a
Out[10]: 
array([[2, 2, 7, 1],
       [5, 0, 3, 1],
       [2, 9, 8, 8],
       [5, 7, 7, 6]])

Some examples on using array_split:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'

# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:                                                                                                                       
[array([[2, 2, 7, 1]]),                                                                                                       
 array([[5, 0, 3, 1],                                                                                                         
       [2, 9, 8, 8]]),                                                                                                        
 array([[5, 7, 7, 6]])]

# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)                                                                                           
Out[5]:                                                                                                                       
[array([[2],                                                                                                                  
       [5],                                                                                                                   
       [2],                                                                                                                   
       [5]]),                                                                                                                 
 array([[2, 7, 1],                                                                                                            
       [0, 3, 1],
       [9, 8, 8],
       [7, 7, 6]])]

An integer as second arg. specifies the number of equal chunks:

In [6]: np.array_split(a, 2, axis=1)
Out[6]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

split works the same but raises an exception if an equal split is not possible

In addition to array_split you can use shortcuts vsplit and hsplit.
vsplit and hsplit are pretty much self-explanatry:

In [11]: np.vsplit(a, 2)
Out[11]: 
[array([[2, 2, 7, 1],
       [5, 0, 3, 1]]),
 array([[2, 9, 8, 8],
       [5, 7, 7, 6]])]

In [12]: np.hsplit(a, 2)
Out[12]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

Char array in a struct - incompatible assignment?

You can try in this way. I had applied this in my case.

#include<stdio.h>

struct name
{

  char first[20];

  char last[30];

};

//globally

// struct name sara={"Sara","Black"};

int main()

 {

//locally

struct name sara={"Sara","Black"};


printf("%s",sara.first);

printf("%s",sara.last);

}

Branch from a previous commit using Git

If you are not sure which commit you want to branch from in advance you can check commits out and examine their code (see source, compile, test) by

git checkout <sha1-of-commit>

once you find the commit you want to branch from you can do that from within the commit (i.e. without going back to the master first) just by creating a branch in the usual way:

git checkout -b <branch_name>

When is del useful in Python?

Once I had to use:

del serial
serial = None

because using only:

serial = None

didn't release the serial port fast enough to immediately open it again. From that lesson I learned that del really meant: "GC this NOW! and wait until it's done" and that is really useful in a lot of situations. Of course, you may have a system.gc.del_this_and_wait_balbalbalba(obj).

Copy array items into another array

With JavaScript ES6, you can use the ... operator as a spread operator which will essentially convert the array into values. Then, you can do something like this:

const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];

const newArray = [
  ...myArray,
  ...moreData,
];

While the syntax is concise, I do not know how this works internally and what the performance implications are on large arrays.

How to merge remote changes at GitHub?

When I got this error, I backed up my entire project folder. Then I did something like

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master

...depending on your branch name (if it's not master).

Then I did git pull --rebase. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.

RecyclerView - Get view at particular position

To get a View from a specific position of recyclerView you need to call findViewHolderForAdapterPosition(position) on recyclerView object that will return RecyclerView.ViewHolder

from the returned RecyclerView.ViewHolder object with itemView you can access all Views at that particular position

RecyclerView.ViewHolder rv_view = recyclerView.findViewHolderForAdapterPosition(position);

ImageView iv_wish = rv_view.itemView.findViewById(R.id.iv_item);

How do I get the picture size with PIL?

Followings gives dimensions as well as channels:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

How to get controls in WPF to fill available space?

Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.

The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.

The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.

Overwriting my local branch with remote branch

first, create a new branch in the current position (in case you need your old 'screwed up' history):

git branch fubar-pin

update your list of remote branches and sync new commits:

git fetch --all

then, reset your branch to the point where origin/branch points to:

git reset --hard origin/branch

be careful, this will remove any changes from your working tree!

send mail from linux terminal in one line

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

OS X Terminal shortcut: Jump to beginning/end of line

Here I found a tweak for this, without any third party tool. This will make the following shortcut to work:

 fn + right: to go to the end of the line.
 fn + left: to go to the beginning of the line.
  • Open terminal preferences.(cmd + ,).
  • Go to your selected theme and then to the keyboard tab.

enter image description here

  • And add a new entry as following. enter image description here enter image description here

  • That's all. Now close and check.

    Hope it helps.

EDIT: Refer to the comment by @Maurice Gilden below for more insights.

How to convert binary string value to decimal

int num = Integer.parseInt("binaryString",2);

syntax error: unexpected token <

The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.

In this case, it expects to find a { (start of JSON); instead it finds a < (start of a heading element).

Successful response:

<html>
  <head></head>
  <body>
    {"foo": "bar", "baz": "qux"}
  </body>
</html>

Not-found response:

<html>
  <head></head>
  <body>
    <h1>Not Found</h1>
    <p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
  </body>
</html>

Try visiting the data endpoint's URL in your browser to see what's returned.

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

What is the difference between g++ and gcc?

GCC: GNU Compiler Collection

  • Referrers to all the different languages that are supported by the GNU compiler.

gcc: GNU C      Compiler
g++: GNU C++ Compiler

The main differences:

  1. gcc will compile: *.c\*.cpp files as C and C++ respectively.
  2. g++ will compile: *.c\*.cpp files but they will all be treated as C++ files.
  3. Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this).
  4. gcc compiling C files has fewer predefined macros.
  5. gcc compiling *.cpp and g++ compiling *.c\*.cpp files has a few extra macros.

Extra Macros when compiling *.cpp files:

#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern

Reverting to a specific commit based on commit id with Git?

git reset c14809fafb08b9e96ff2879999ba8c807d10fb07 is what you're after...

Is there a unique Android device ID?

I think this is sure fire way of building a skeleton for a unique ID... check it out.

Pseudo-Unique ID, that works on all Android devices Some devices don't have a phone (eg. Tablets) or for some reason, you don't want to include the READ_PHONE_STATE permission. You can still read details like ROM Version, Manufacturer name, CPU type, and other hardware details, that will be well suited if you want to use the ID for a serial key check, or other general purposes. The ID computed in this way won't be unique: it is possible to find two devices with the same ID (based on the same hardware and ROM image) but the changes in real-world applications are negligible. For this purpose you can use the Build class:

String m_szDevIDShort = "35" + //we make this look like a valid IMEI
            Build.BOARD.length()%10+ Build.BRAND.length()%10 +
            Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
            Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
            Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
            Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
            Build.TAGS.length()%10 + Build.TYPE.length()%10 +
            Build.USER.length()%10 ; //13 digits

Most of the Build members are strings, what we're doing here is to take their length and transform it via modulo in a digit. We have 13 such digits and we are adding two more in front (35) to have the same size ID as the IMEI (15 digits). There are other possibilities here are well, just have a look at these strings. Returns something like 355715565309247. No special permission is required, making this approach very convenient.


(Extra info: The technique given above was copied from an article on Pocket Magic.)

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

How to redirect to the same page in PHP

I use correctly in localhost:

header('0');

How to start anonymous thread class

Just call start()

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();

How to assign an action for UIImageView object in Swift

For swift 2.0 and above do this

@IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
    }
    func tappedMe()
    {
        print("Tapped on Image")
    }

How to concatenate strings with padding in sqlite

SQLite has a printf function which does exactly that:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

How to compare two List<String> to each other?

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

if (a1.SequenceEqual(a2))

See it working online: ideone

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

Should URL be case sensitive?

Case Preservation

URLs are case-preserving, between client and server. But portions of URLs may or may not be case-sensitive, depending on the server, for a couple of reasons.

Case Sensitivity

The following bold parts of URLs may be case-sensitive, depending on the site and/or server configuration.

    http:// www. example.com /abc/def.ghi?jkl=mno#pqr

    user @ example.com

Rationale

Case-sensitivity in URLs can have several uses. Mainly:

  1. Native compatibility with case-sensitive filesystems.
  2. More compact data encoding within URLs, such as for serialization, hashing, IDs, permalinks, and URL shorteners.

As a developer, I believe the above can often be handled in better ways, but I also understand there are cases where a situation may not permit this.

For example, imagine an existing product that requires a lot of data placed in the "GET" URL, yet it must be compatible with the maximum URL lengths of all major servers, browsers, and caching/proxy mechanisms. To fit even a moderate-length command string (under 1,024 characters for some older browsers), you'd need to use every unique URL-safe character you could (which is basically what base64url encoding is).

In an Ideal World

Whether or not URLs should be case-sensitive is debatable. I personally believe they should not be, for simplicity (though it may create longer URLs, we have percent-escapes to easily handle cases where we must ensure preservation of exact characters, and there are ways to transfer data other than right in the URL).

Many seem to agree based on the fact that case-insensitive URLs are explicitly enabled for many popular sites and services, in order to increase usability. The most prominent example is the username portion of email addresses. Most email providers will ignore case and sometimes even dots and other symbols (like "[email protected]" being the same as "[email protected]"). Even though email usernames are case-sensitive by default, according to spec.

However, the fact is that despite what I or others might want, this is the state of how things currently work. And while an eventual worldwide transition to a case-insensitive URL standard is certainly possible, it would likely take quite a long time since case-sensitivity is currently used extensively around the web for various purposes.

Best Practices

As far as best practices go, as a user you can reasonably stick to lowercase for most situations and expect things to work. The main exceptions would be URLs that use case-based encoding or document paths with direct filesystem equivalents. However, such complex URLs are typically copy-pasted (or simply clicked) rather than manually typed.

As a web developer, you should consider keeping URLs as case-insensitive as possible. Though there are clearly some difficult-to-avoid situations, depending on context, as noted above.

SQL Server - Return value after INSERT

After doing an insert into a table with an identity column, you can reference @@IDENTITY to get the value: http://msdn.microsoft.com/en-us/library/aa933167%28v=sql.80%29.aspx

Setting Camera Parameters in OpenCV/Python

I wasn't able to fix the problem OpenCV either, but a video4linux (V4L2) workaround does work with OpenCV when using Linux. At least, it does on my Raspberry Pi with Rasbian and my cheap webcam. This is not as solid, light and portable as you'd like it to be, but for some situations it might be very useful nevertheless.

Make sure you have the v4l2-ctl application installed, e.g. from the Debian v4l-utils package. Than run (before running the python application, or from within) the command:

v4l2-ctl -d /dev/video1 -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=10

It overwrites your camera shutter time to manual settings and changes the shutter time (in ms?) with the last parameter to (in this example) 10. The lower this value, the darker the image.

VS 2017 Metadata file '.dll could not be found

For me cleaning and building didn't work. Unloading the project didn't work. Restarting Visual Studio or even the pc didn't work. This is what did work:

Go to each of the projects that are throwing the error, and in References, delete the reference to the problematic project and add it again. That solves the issue.

The problem seems to be related to moving a project around (Move it inside a folder for example), then a different project that references it, have its path wrong and can't find it.

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

Spring Boot without the web server

Remove folowing dependancy on your pom file will work for me

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

ImportError: No module named model_selection

Update sklearn

conda update scikit-learn

Get property value from string using reflection

Great answer by jheddings. I would like to improve it by allowing referencing of aggregated arrays or collections of objects, so that propertyName could be property1.property2[X].property3:

    public static object GetPropertyValue(object srcobj, string propertyName)
    {
        if (srcobj == null)
            return null;

        object obj = srcobj;

        // Split property name to parts (propertyName could be hierarchical, like obj.subobj.subobj.property
        string[] propertyNameParts = propertyName.Split('.');

        foreach (string propertyNamePart in propertyNameParts)
        {
            if (obj == null)    return null;

            // propertyNamePart could contain reference to specific 
            // element (by index) inside a collection
            if (!propertyNamePart.Contains("["))
            {
                PropertyInfo pi = obj.GetType().GetProperty(propertyNamePart);
                if (pi == null) return null;
                obj = pi.GetValue(obj, null);
            }
            else
            {   // propertyNamePart is areference to specific element 
                // (by index) inside a collection
                // like AggregatedCollection[123]
                //   get collection name and element index
                int indexStart = propertyNamePart.IndexOf("[")+1;
                string collectionPropertyName = propertyNamePart.Substring(0, indexStart-1);
                int collectionElementIndex = Int32.Parse(propertyNamePart.Substring(indexStart, propertyNamePart.Length-indexStart-1));
                //   get collection object
                PropertyInfo pi = obj.GetType().GetProperty(collectionPropertyName);
                if (pi == null) return null;
                object unknownCollection = pi.GetValue(obj, null);
                //   try to process the collection as array
                if (unknownCollection.GetType().IsArray)
                {
                    object[] collectionAsArray = unknownCollection as object[];
                    obj = collectionAsArray[collectionElementIndex];
                }
                else
                {
                    //   try to process the collection as IList
                    System.Collections.IList collectionAsList = unknownCollection as System.Collections.IList;
                    if (collectionAsList != null)
                    {
                        obj = collectionAsList[collectionElementIndex];
                    }
                    else
                    {
                        // ??? Unsupported collection type
                    }
                }
            }
        }

        return obj;
    }

How to do IF NOT EXISTS in SQLite

You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"

When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.

SQLite Documentation

How to remove listview all items

if you used List object and passed to the adapter you can remove the value from the List object and than call the notifyDataSetChanged() using adapter object.

for e.g.

List<String> list = new ArrayList<String>();
ArrayAdapter adapter;


adapter = new ArrayAdapter<String>(DeleteManyTask.this, 
            android.R.layout.simple_list_item_1,
            (String[])list.toArray(new String[0]));

listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);

listview.setAdapter(listAdapter);

for remove do this way

list.remove(index); //or
list.clear();
adpater.notifyDataSetChanged();

or without list object remove item from list.

adapter.clear();
adpater.notifyDataSetChanged();

How to get a list of user accounts using the command line in MySQL?

The mysql.db table is possibly more important in determining user rights. I think an entry in it is created if you mention a table in the GRANT command. In my case the mysql.users table showed no permissions for a user when it obviously was able to connect and select, etc.

mysql> select * from mysql.db;
mysql> select * from db;
+---------------+-----------------+--------+-------------+-------------+-------------+--------
| Host          | Db              | User   | Select_priv | Insert_priv | Update_priv | Del...

Android Studio - Unable to find valid certification path to requested target

I got it because I'm behind a proxy. I had set the http but not the https proxy in gradle.properties. Https was needed in this case:

systemProp.http.proxyHost=<host>
systemProp.http.proxyPort=<port>
systemProp.https.proxyHost=<host>
systemProp.https.proxyPort=<port>

Also, take a look at the Android Studio logs for where the error could be.

Find and Replace Inside a Text File from a Bash Command

Be careful if you replace URLs with "/" character.

An example of how to do it:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

How to check if a variable is equal to one string or another string?

for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
        if createunicode(a.text) in ['<','<']:
            links.append(a.attrMap['href'])
        else:
            continue

It works for me.

Find unique rows in numpy.array

Yet another possible solution

np.vstack({tuple(row) for row in a})

How to set the value of a hidden field from a controller in mvc

if you are not using model as per your question you can do like this

@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })

else if you are using model (considering passing model has hdnFlag property), you can use this approch

@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})

Confirmation before closing of tab/browser

Try this:

<script>
    window.onbeforeunload = function(e) {
       return 'Dialog text here.';
    };
</script>

more info here MDN.

How To Run PHP From Windows Command Line in WAMPServer

The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.

Try running

php -m

And see if "readline" appears in the output.

There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:

php file.php

There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).

Edit: According to the documentation here, readline is not supported under Windows:

Note: This extension is not available on Windows platforms.

So, if that is correct, your options are:

  • Avoid the interactive shell, and just execute PHP code in files from the command line - this should work well
  • Try getting phpsh to work under Windows

SQL: capitalize first letter only

select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

Why do I keep getting Delete 'cr' [prettier/prettier]?

Try setting the "endOfLine":"auto" in your .prettierrc file (inside the object)

Or set

"prettier/prettier": ["error", {
     ..
    "endOfLine":"auto"
     ..
  }],

inside the rules object of the eslintrc file.

If you are using windows machine endOfLine can be "crlf" basing on your git config.

List all files and directories in a directory + subdirectories

The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.

Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.

    public class StackBasedIteration
{
    static void Main(string[] args)
    {
        // Specify the starting folder on the command line, or in 
        // Visual Studio in the Project > Properties > Debug pane.
        TraverseTree(args[0]);

        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    public static void TraverseTree(string root)
    {
        // Data structure to hold names of subfolders to be
        // examined for files.
        Stack<string> dirs = new Stack<string>(20);

        if (!System.IO.Directory.Exists(root))
        {
            throw new ArgumentException();
        }
        dirs.Push(root);

        while (dirs.Count > 0)
        {
            string currentDir = dirs.Pop();
            string[] subDirs;
            try
            {
                subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
            }
            // An UnauthorizedAccessException exception will be thrown if we do not have
            // discovery permission on a folder or file. It may or may not be acceptable 
            // to ignore the exception and continue enumerating the remaining files and 
            // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
            // will be raised. This will happen if currentDir has been deleted by
            // another application or thread after our call to Directory.Exists. The 
            // choice of which exceptions to catch depends entirely on the specific task 
            // you are intending to perform and also on how much you know with certainty 
            // about the systems on which this code will run.
            catch (UnauthorizedAccessException e)
            {                    
                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            string[] files = null;
            try
            {
                files = System.IO.Directory.EnumerateFiles(currentDir);
            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine(e.Message);
                continue;
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }
            // Perform the required action on each file here.
            // Modify this block to perform your required task.
            foreach (string file in files)
            {
                try
                {
                    // Perform whatever action is required in your scenario.
                    System.IO.FileInfo fi = new System.IO.FileInfo(file);
                    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // If file was deleted by a separate application
                    //  or thread since the call to TraverseTree()
                    // then just continue.
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (UnauthorizedAccessException e)
                {                    
                    Console.WriteLine(e.Message);
                    continue;
                }
            }

            // Push the subdirectories onto the stack for traversal.
            // This could also be done before handing the files.
            foreach (string str in subDirs)
                dirs.Push(str);
        }
    }
}

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to download a file with Node.js (without using third-party libraries)?

Here's yet another way to handle it without 3rd party dependency and also searching for redirects:

        var download = function(url, dest, cb) {
            var file = fs.createWriteStream(dest);
            https.get(url, function(response) {
                if ([301,302].indexOf(response.statusCode) !== -1) {
                    body = [];
                    download(response.headers.location, dest, cb);
                  }
              response.pipe(file);
              file.on('finish', function() {
                file.close(cb);  // close() is async, call cb after close completes.
              });
            });
          }

How to use template module with different set of variables?

Another real world example using a list

an extract for a template for php.ini

{% if 'cli/php.ini' in item.d %}
max_execution_time = 0
memory_limit = 1024M
{% else %}
max_execution_time = 300
memory_limit = 512M
{% endif %}

This is the var

php_templates:
  - { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/apache2/php.ini" }
  - { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/cli/php.ini" }

Then i deploy with this

- name: push templated files
  template:
    src: "{{item.s}}"
    dest: "{{item.d}}"
    mode: "{{item.m | default(0644) }}"
    owner: "{{item.o | default('root') }}"
    group: "{{item.g | default('root') }}"
    backup: yes
  with_items: "{{php_templates}}"

What is the best open-source java charting library? (other than jfreechart)

Good question, I was just looking for alternatives to JFreeChart myself the other day. JFreeChart is excellent and very comprehensive, I've used it on several projects. My recent problem was that it meant adding 1.6mb of libraries to a 50kb applet, so I was looking for something smaller.

The JFreeChart FAQ itself lists alternatives. Compared to JFreeChart, most of them are pretty basic, and some pretty ugly. The most promising seem to be the Java Chart Construction Kit and OpenChart2.

I also found EasyCharts, which is a commercial product but seemingly free to use in some circumstances.

In the end, I went back to the tried and trusted JFreeChart and used Proguard to butcher it into a more manageable size.

I suggest that you take another look at JFreeChart. The user guide is only available to buy, but the demo shows what is possible and it's pretty easy to work out how from the API documentation. Basically you start with the ChartFactory static methods and plug the resultant JFreeChart object into a ChartPanel to display it. If you get stuck, I'm sure you'll get some quick answers to your problems on StackOverflow.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had the same problem. It was caused because I compiled the Boost with the Visual C++ 2010(v100) and I tried to use the library with the Visual Studio 2012 (v110) by mistake.

So, I changed the configurations (in Visual Studio 2012) going to Project properties -> General -> Plataform Toolset and change the value from Visual Studio 2012 (v110) to Visual Studio 2010 (v100).

jQuery .get error response function?

If you want a generic error you can setup all $.ajax() (which $.get() uses underneath) requests jQuery makes to display an error using $.ajaxSetup(), for example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error);
  }
});

Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error option to default to the handler/function above, if you made a full $.ajax() call and specified the error handler then what you had would override the above.

Find unique lines

I find this easier.

sort -u input_filename > output_filename

-u stands for unique.

Convert character to ASCII code in JavaScript

To convert a String to a cumulative number:

_x000D_
_x000D_
const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);

console.log(stringToSum("A"));              // 65
console.log(stringToSum("Roko"));           // 411
console.log(stringToSum("Stack Overflow")); // 1386
_x000D_
_x000D_
_x000D_

Use case:

Say you want to generate different background colors depending on a username:

_x000D_
_x000D_
const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);

const UI_userIcon = user => {
  const hue = (stringToSum(user.name) - 65) % 360; // "A" = hue: 0
  console.log(`Hue: ${hue}`);
  return `<div class="UserIcon" style="background:hsl(${hue}, 80%, 60%)" title="${user.name}">
    <span class="UserIcon-letter">${user.name[0].toUpperCase()}</span>
  </div>`;
};

[
  {name:"A"},
  {name:"Amanda"},
  {name:"amanda"},
  {name:"Anna"},
].forEach(user => {
  document.body.insertAdjacentHTML("beforeend", UI_userIcon(user));
});
_x000D_
.UserIcon {
  width: 4em;
  height: 4em;
  border-radius: 4em;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.UserIcon-letter {
  font: 700 2em/0 sans-serif;
  color: #fff;
}
_x000D_
_x000D_
_x000D_

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

python: Change the scripts working directory to the script's own directory

You can get a shorter version by using sys.path[0].

os.chdir(sys.path[0])

From http://docs.python.org/library/sys.html#sys.path

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

LINQ order by null column where order is ascending and nulls should be last

Below is extension method to check for null if you want to sort on child property of a keySelector.

public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
    return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}

And simple use it like:

var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);

How do you sort a dictionary by value?

You do not sort entries in the Dictionary. Dictionary class in .NET is implemented as a hashtable - this data structure is not sortable by definition.

If you need to be able to iterate over your collection (by key) - you need to use SortedDictionary, which is implemented as a Binary Search Tree.

In your case, however the source structure is irrelevant, because it is sorted by a different field. You would still need to sort it by frequency and put it in a new collection sorted by the relevant field (frequency). So in this collection the frequencies are keys and words are values. Since many words can have the same frequency (and you are going to use it as a key) you cannot use neither Dictionary nor SortedDictionary (they require unique keys). This leaves you with a SortedList.

I don't understand why you insist on maintaining a link to the original item in your main/first dictionary.

If the objects in your collection had a more complex structure (more fields) and you needed to be able to efficiently access/sort them using several different fields as keys - You would probably need a custom data structure that would consist of the main storage that supports O(1) insertion and removal (LinkedList) and several indexing structures - Dictionaries/SortedDictionaries/SortedLists. These indexes would use one of the fields from your complex class as a key and a pointer/reference to the LinkedListNode in the LinkedList as a value.

You would need to coordinate insertions and removals to keep your indexes in sync with the main collection (LinkedList) and removals would be pretty expensive I'd think. This is similar to how database indexes work - they are fantastic for lookups but they become a burden when you need to perform many insetions and deletions.

All of the above is only justified if you are going to do some look-up heavy processing. If you only need to output them once sorted by frequency then you could just produce a list of (anonymous) tuples:

var dict = new SortedDictionary<string, int>();
// ToDo: populate dict

var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();

foreach (var entry in output)
{
    Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

Raise an event whenever a property's value changed?

public event EventHandler ImageFullPath1Changed;

public string ImageFullPath1
{
    get
    {
        // insert getter logic
    }
    set
    {
        // insert setter logic       

        // EDIT -- this example is not thread safe -- do not use in production code
        if (ImageFullPath1Changed != null && value != _backingField)
            ImageFullPath1Changed(this, new EventArgs(/*whatever*/);
    }
}                        

That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

Encrypt & Decrypt using PyCrypto AES 256

You can get a passphrase out of an arbitrary password by using a cryptographic hash function (NOT Python's builtin hash) like SHA-1 or SHA-256. Python includes support for both in its standard library:

import hashlib

hashlib.sha1("this is my awesome password").digest() # => a 20 byte string
hashlib.sha256("another awesome password").digest() # => a 32 byte string

You can truncate a cryptographic hash value just by using [:16] or [:24] and it will retain its security up to the length you specify.

How can I set size of a button?

Try with setPreferredSize instead of setSize.

UPDATE: GridLayout take up all space in its container, and BoxLayout seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.

Since GridLayout make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.

import javax.swing.*;
import java.awt.*;

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel(new GridLayout(4, 4));
        firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                firstPanel.add(new JButton());
            }
        }

        JPanel firstGluePanel = new JPanel(new BorderLayout());
        firstGluePanel.add(firstPanel, BorderLayout.WEST);
        firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        JPanel secondPanel = new JPanel(new GridLayout(13, 5));
        secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                secondPanel.add(new JButton());
            }
        }

        JPanel secondGluePanel = new JPanel(new BorderLayout());
        secondGluePanel.add(secondPanel, BorderLayout.WEST);
        secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        mainPanel.add(firstGluePanel);
        mainPanel.add(secondGluePanel);
        frame.getContentPane().add(mainPanel);

        //frame.setSize(400,600);
        frame.pack();
        frame.setVisible(true);
    }
}

How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then [IO.Path]::Combine won't have the params string[] overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

Join-Path C: (Join-Path  "Program Files" "Microsoft Office")

or

Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

Convert JavaScript String to be all lower case?

In case you want to build it yourself:

function toLowerCase(string) {

let lowerCaseString = "";

for (let i = 0; i < string.length; i++) {
    //find ASCII charcode
    let charcode = string.charCodeAt(i);

    //if uppercase
    if (charcode > 64 && charcode < 97){
        //convert to lowercase
        charcode = charcode + 32
    }

    //back to char
    let lowercase = String.fromCharCode(charcode);

    //append
    lowerCaseString = lowerCaseString.concat(lowercase);
}

return lowerCaseString

}

Java 8 - Difference between Optional.flatMap and Optional.map

Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.

As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:

void doSome(Optional<Person> person){
  /*and here you want to retrieve some property phone out of person
    you may write something like this:
  */
  Optional<String> phone = person.map((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}
class Person{
  private String phone;
  //setter, getters
}

Here you have returned a String type which is automatically wrapped in an Optional type.

If person class looked like this, i.e. phone is also Optional

class Person{
  private Optional<String> phone;
  //setter,getter
}

In this case invoking map function will wrap the returned value in Optional and yield something like:

Optional<Optional<String>> 
//And you may want Optional<String> instead, here comes flatMap

void doSome(Optional<Person> person){
  Optional<String> phone = person.flatMap((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}

PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Dynamically updating plot in matplotlib

Is there a way in which I can update the plot just by adding more point[s] to it...

There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

Then when you receive data from the serial port just call update_line.

What are the differences between "=" and "<-" assignment operators in R?

What are the differences between the assignment operators = and <- in R?

As your example shows, = and <- have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax in R gives the following operator precedence table, from highest to lowest:

…
‘-> ->>’           rightwards assignment
‘<- <<-’           assignment (right to left)
‘=’                assignment (right to left)
…

But is this the only difference?

Since you were asking about the assignment operators: yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps claims that there are more differences:

The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Let’s not put too fine a point on it: the R documentation is wrong. This is easy to show: we just need to find a counter-example of the = operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …}). — Without further ado:

x
# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
x
# [1] 1

Clearly we’ve performed an assignment, using =, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?

It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):

  1. The first meaning is as an assignment operator. This is all we’ve talked about so far.
  2. The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the = operator it performs no action at runtime, it merely changes the way an expression is parsed.

So how does R decide whether a given usage of = refers to the operator or to named argument passing? Let’s see.

In any piece of code of the general form …

‹function_name›(‹argname› = ‹value›, …)
‹function_name›(‹args›, ‹argname› = ‹value›, …)

… the = is the token that defines named argument passing: it is not the assignment operator. Furthermore, = is entirely forbidden in some syntactic contexts:

if (‹var› = ‹value›) …
while (‹var› = ‹value›) …
for (‹var› = ‹value› in ‹value2›) …
for (‹var1› in ‹var2› = ‹value›) …

Any of these will raise an error “unexpected '=' in ‹bla›”.

In any other context, = refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment. For instance, the following performs assignment:

median((x = 1 : 10))

But also:

if (! (nf = length(from))) return()

Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy function (replacing <- with =) — it’s a pervasive pattern in much of the core R codebase.

The original explanation by John Chambers, which the the R documentation is probably based on, actually explains this correctly:

[= assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.


In sum, by default the operators <- and = do the same thing. But either of them can be overridden separately to change its behaviour. By contrast, <- and -> (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans.

C fopen vs open

fopen vs open in C

1) fopen is a library function while open is a system call.

2) fopen provides buffered IO which is faster compare to open which is non buffered.

3) fopen is portable while open not portable (open is environment specific).

4) fopen returns a pointer to a FILE structure(FILE *); open returns an integer that identifies the file.

5) A FILE * gives you the ability to use fscanf and other stdio functions.

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

In my case it was python path issue.

#1 First set your PYTHONPATH

#2 then set DJANGO_SETTINGS_MODULE

then run django-admin shell command (django-admin dbshell)
(venv) shakeel@workstation:~/project_path$ export PYTHONPATH=/home/shakeel/project_path
(venv) shakeel@workstation:~/project_path$ export DJANGO_SETTINGS_MODULE=my_project.settings
(venv) shakeel@workstation:~/project_path$ django-admin dbshell
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite>

otherwise python manage.py shell works like charm.

Remove empty array elements

$out_array = array_filter($input_array, function($item) 
{ 
    return !empty($item['key_of_array_to_check_whether_it_is_empty']); 
}
);

PHP, display image with Header()

if you know the file name, but don't know the file extention you can use this function:

public function showImage($name)
    {

         $types = [
             'gif'=> 'image/gif',
             'png'=> 'image/png',
             'jpeg'=> 'image/jpeg',
             'jpg'=> 'image/jpeg',
         ];
         $root_path  = '/var/www/my_app'; //use your framework to get this properly ..
         foreach($types as $type=>$meta){
             if(file_exists($root_path .'/uploads/'.$name  .'.'. $type)){
                 header('Content-type: ' . $meta);
                 readfile($root_path .'/uploads/'.$name .'.'. $type);
                 return;
             }
         }
    }

Note: the correct content-type for JPG files is image/jpeg.

Is there a simple way to remove multiple spaces in a string?

In some cases it's desirable to replace consecutive occurrences of every whitespace character with a single instance of that character. You'd use a regular expression with backreferences to do that.

(\s)\1{1,} matches any whitespace character, followed by one or more occurrences of that character. Now, all you need to do is specify the first group (\1) as the replacement for the match.

Wrapping this in a function:

import re

def normalize_whitespace(string):
    return re.sub(r'(\s)\1{1,}', r'\1', string)
>>> normalize_whitespace('The   fox jumped   over    the log.')
'The fox jumped over the log.'
>>> normalize_whitespace('First    line\t\t\t \n\n\nSecond    line')
'First line\t \nSecond line'

Find location of a removable SD card

I had an application that used a ListPreference where the user was required to select the location of where they wanted to save something.

In that app, I scanned /proc/mounts and /system/etc/vold.fstab for sdcard mount points. I stored the mount points from each file into two separate ArrayLists.

Then, I compared one list with the other and discarded items that were not in both lists. That gave me a list of root paths to each sdcard.

From there, I tested the paths with File.exists(), File.isDirectory(), and File.canWrite(). If any of those tests were false, I discarded that path from the list.

Whatever was left in the list, I converted to a String[] array so it could be used by the ListPreference values attribute.

You can view the code here: http://sapienmobile.com/?p=204

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

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.

Counting Chars in EditText Changed Listener

TextWatcher maritalStatusTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        try {
            if (charSequence.length()==0){
                topMaritalStatus.setVisibility(View.GONE);
            }else{
                topMaritalStatus.setVisibility(View.VISIBLE);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

Does Java have a path joining method?

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.

How do I POST XML data with curl

You can try the following solution:

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

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

Arrays.asList() of an array

Use java.utils.Arrays:

public int getTheNumber(int[] factors) {
    int[] f = (int[])factors.clone();
    Arrays.sort(f);
    return f[0]*f[(f.length-1];
}

Or if you want to be efficient avoid all the object allocation just actually do the work:

public static int getTheNumber(int[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException();
    int min = array[0];
    int max = array[0];
    for (int i = 1; i< array.length;++i) {
        int v = array[i];
        if (v < min) {
            min = v;
        } else if (v > max) {
            max = v;
        }
    }
    return min * max;
}

How to extract text from a PDF?

One of the comments here used gs on Windows. I had some success with that on Linux/OSX too, with the following syntax:

gs \
 -q \
 -dNODISPLAY \
 -dSAFER \
 -dDELAYBIND \
 -dWRITESYSTEMDICT \
 -dSIMPLE \
 -f ps2ascii.ps \
 "${input}" \
 -dQUIET \
 -c quit

I used dSIMPLE instead of dCOMPLEX because the latter outputs 1 character per line.

Which comes first in a 2D array, rows or columns?

In TStringGrid cells property Col come first.

Property Cells[ACol, ARow: Integer]: string read GetCells write SetCells;

So the assignment StringGrid1.cells[2, 1] := 'abcde'; the value is displayed in the third column second row.

How do I increase the capacity of the Eclipse output console?

Eclipse has limit of 32000 characters per line. If you have, for example JSONObject, which you want to log into console, you won't succeed. You can't handle this with the checkbox. Tested

Returning IEnumerable<T> vs. IQueryable<T>

Yes, both will give you deferred execution.

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.

In code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

To add to Alan Wells's elaborate answer here is a quick fix

Run a Local Server

you can serve any folder in your computer with Serve

First, navigate using the command line into the folder you'd like to serve.

Then

npx i -g serve
serve

or if you'd like to test Serve without downloading it

npx serve

and that's it! You can view your files at http://localhost:5000

enter image description here

What are some examples of commonly used practices for naming git branches?

Here are some branch naming conventions that I use and the reasons for them

Branch naming conventions

  1. Use grouping tokens (words) at the beginning of your branch names.
  2. Define and use short lead tokens to differentiate branches in a way that is meaningful to your workflow.
  3. Use slashes to separate parts of your branch names.
  4. Do not use bare numbers as leading parts.
  5. Avoid long descriptive names for long-lived branches.

Group tokens

Use "grouping" tokens in front of your branch names.

group1/foo
group2/foo
group1/bar
group2/bar
group3/bar
group1/baz

The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity.

Short well-defined tokens

Choose short tokens so they do not add too much noise to every one of your branch names. I use these:

wip       Works in progress; stuff I know won't be finished soon
feat      Feature I'm adding or expanding
bug       Bug fix or experiment
junk      Throwaway branch created to experiment

Each of these tokens can be used to tell you to which part of your workflow each branch belongs.

It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in.

new/frabnotz
new/foo
new/bar
test/foo
test/frabnotz
ver/foo

You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options.

$ git branch --list "test/*"
test/foo
test/frabnotz

$ git branch --list "*/foo"
new/foo
test/foo
ver/foo

$ gitk --branches="*/foo"

Use slashes to separate parts

You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote.

$ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*'
$ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*'

For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones.

$ git checkout new<TAB>
Menu:  new/frabnotz   new/foo   new/bar


$ git checkout foo<TAB>
Menu:  new/foo   test/foo   ver/foo

(Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.)

It also lets you search for branches in many git commands, like this:

git branch --list "feature/*"
git log --graph --oneline --decorate --branches="feature/*" 
gitk --branches="feature/*" 

Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named "foo" and another branch named "foo/bar". This can be confusing for new users.

Do not use bare numbers

Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion.

$ git checkout CR15032<TAB>
Menu:   fix/CR15032    test/CR15032

If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited.

Avoid long descriptive names

Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log.

On the other hand long branch names can be more helpful in "merge commits" if you do not habitually rewrite them by hand. The default merge commit message is Merge branch 'branch-name'. You may find it more helpful to have merge messages show up as Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted' instead of just Merge branch 'fix/CR15032'.

TypeError: $ is not a function when calling jQuery function

(function( $ ) {
  "use strict";

  $(function() {

    //Your code here

  });

}(jQuery));

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

Are there any naming convention guidelines for REST APIs?

I don't think the camel case is the issue in that example, but I imagine a more RESTful naming convention for the above example would be:

api.service.com/helloWorld/userId/x

rather then making userId a query parameter (which is perfectly legal) my example denotes that resource in, IMO, a more RESTful way.

Random / noise functions for GLSL

After the initial posting of this question in 2010, a lot has changed in the realm of good random functions and hardware support for them.

Looking at the accepted answer from today's perspective, this algorithm is very bad in uniformity of the random numbers drawn from it. And the uniformity suffers a lot depending on the magnitude of the input values and visible artifacts/patterns will become apparent when sampling from it for e.g. ray/path tracing applications.

There have been many different functions (most of them integer hashing) being devised for this task, for different input and output dimensionality, most of which are being evaluated in the 2020 JCGT paper Hash Functions for GPU Rendering. Depending on your needs you could select a function from the list of proposed functions in that paper and simply from the accompanying Shadertoy. One that isn't covered in this paper but that has served me very well without any noticeably patterns on any input magnitude values is also one that I want to highlight.

Other classes of algorithms use low-discrepancy sequences to draw pseudo-random numbers from, such as the Sobol squence with Owen-Nayar scrambling. Eric Heitz has done some amazing research in this area, as well with his A Low-Discrepancy Sampler that Distributes Monte Carlo Errors as a Blue Noise in Screen Space paper. Another example of this is the (so far latest) JCGT paper Practical Hash-based Owen Scrambling, which applies Owen scrambling to a different hash function (namely Laine-Karras).

Yet other classes use algorithms that produce noise patterns with desirable frequency spectrums, such as blue noise, that is particularly "pleasing" to the eyes.

(I realize that good StackOverflow answers should provide the algorithms as source code and not as links because those can break, but there are way too many different algorithms nowadays and I intend for this answer to be a summary of known-good algorithms today)

How to determine MIME type of file in android?

Optimized version of Jens' answere with null-safety and fallback-type.

@NonNull
static String getMimeType(@NonNull File file) {
    String type = null;
    final String url = file.toString();
    final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    }
    if (type == null) {
        type = "image/*"; // fallback type. You might set it to */*
    }
    return type;
}

Important: getFileExtensionFromUrl() only works with lowercase!


Update (19.03.2018)

Bonus: Above methods as a less verbose Kotlin extension function:

fun File.getMimeType(fallback: String = "image/*"): String {
    return MimeTypeMap.getFileExtensionFromUrl(toString())
            ?.run { MimeTypeMap.getSingleton().getMimeTypeFromExtension(toLowerCase()) }
            ?: fallback // You might set it to */*
}

How to quit a java app from within the program

This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

Default optional parameter in Swift function

If you want to be able to call the func with or without the parameter you can create a second func of the same name which calls the other.

func test(firstThing: Int?) {
    if firstThing != nil {
        print(firstThing!)
    }
    print("done")
}

func test() {
    test(firstThing: nil)
}

now you can call a function named test without or without the parameter.

// both work
test()
test(firstThing: 5)

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:

$.post('/Branch/Details/' + id, function(result) {
    // Do something with the result like for example inject it into
    // some placeholder and update the DOM.
    // This obviously assumes that your controller action returns
    // a partial view otherwise you will break your markup
});

On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.

So if you only wanted to redirect the browser:

function foo(id) {
    window.location.href = '/Branch/Details/' + id;
}

As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Remove item from list based on condition

If you have LINQ:

var itemtoremove = prods.Where(item => item.ID == 1).First();
prods.Remove(itemtoremove)

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

How to use JUnit to test asynchronous processes

Start the process off and wait for the result using a Future.

Get elements by attribute when querySelectorAll is not available without using libraries?

That works too:

document.querySelector([attribute="value"]);

So:

document.querySelector([data-foo="bar"]);

Select count(*) from multiple tables

A quick stab came up with:

Select (select count(*) from Table1) as Count1, (select count(*) from Table2) as Count2

Note: I tested this in SQL Server, so From Dual is not necessary (hence the discrepancy).

Convert varchar to float IF ISNUMERIC

You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.

SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END

Get the string value from List<String> through loop for display

pst = con.createStatement(); ResultSet resultSet= pst.executeQuery(query);

     String str1 = "<table>";
     int i = 1;
    while(resultSet.next()) {
             str1+= "</tr><td>"+i+"</td>"+
             "<td>"+resultSet.getString("first_name")+"</td>"+
             "<td>"+resultSet.getString("last_name")+"</td>"+
             "<td>"+resultSet.getString("email_id")+"</td>"+
             "<td>"+resultSet.getString("dob") +"</td>"+

             "</tr>";
        i++;

    }
        str1 =str1+"<table>";

    model.addAttribute("list",str1);

    return "userlist";  //Sending to views .jsp 

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

Any way to make a WPF textblock selectable?

According to Windows Dev Center:

TextBlock.IsTextSelectionEnabled property

[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see the archive ]

Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API.

Add hover text without javascript like we hover on a user's reputation

You're looking for tooltip

For the basic tooltip, you want:

<div title="This is my tooltip">

For a fancier javascript version, you can look into:

http://www.designer-daily.com/jquery-prototype-mootool-tooltips-12632

The above link gives you 12 options for tooltips.

How do you set the max number of characters for an EditText in Android?

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_edittext_length"

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

How to remove specific object from ArrayList in Java?

I have tried this and it works for me:

ArrayList<cartItem> cartItems= new ArrayList<>();

//filling the cartItems

cartItem ci=new cartItem(itemcode,itemQuantity);//the one I want to remove

Iterator<cartItem> itr =cartItems.iterator();
while (itr.hasNext()){
   cartItem ci_itr=itr.next();
   if (ci_itr.getClass() == ci.getClass()){
      itr.remove();
      return;
    }
}

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

OpenCV with Network Cameras

I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.

#include "cv.h"
#include "highgui.h"
#include <iostream>

int main(int, char**) {
    cv::VideoCapture vcap;
    cv::Mat image;

    const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp"; 
    /* it may be an address of an mjpeg stream, 
    e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */

    //open the video stream and make sure it's opened
    if(!vcap.open(videoStreamAddress)) {
        std::cout << "Error opening video stream or file" << std::endl;
        return -1;
    }

    //Create output window for displaying frames. 
    //It's important to create this window outside of the `for` loop
    //Otherwise this window will be created automatically each time you call
    //`imshow(...)`, which is very inefficient. 
    cv::namedWindow("Output Window");

    for(;;) {
        if(!vcap.read(image)) {
            std::cout << "No frame" << std::endl;
            cv::waitKey();
        }
        cv::imshow("Output Window", image);
        if(cv::waitKey(1) >= 0) break;
    }   
}

Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:

// H.264 stream RTSP address, where 10.10.10.10 is an IP address 
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp

// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp

Query to display all tablespaces in a database and datafiles

If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:

SQL> connect SYSTEM/fyicenter
Connected.

SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
  2  FROM USER_TABLESPACES;
TABLESPACE_NAME                STATUS    CONTENTS
------------------------------ --------- ---------
SYSTEM                         ONLINE    PERMANENT
UNDO                           ONLINE    UNDO
SYSAUX                         ONLINE    PERMANENT
TEMP                           ONLINE    TEMPORARY
USERS                          ONLINE    PERMANENT

http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html

Visual studio code terminal, how to run a command with administrator rights?

Option 1 - Easier & Persistent

Running Visual Studio Code as Administrator should do the trick.

If you're on Windows you can:

  1. Right click the shortcut or app/exe
  2. Go to properties
  3. Compatibility tab
  4. Check "Run this program as an administrator"
There is a caveat to it though

Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.

Related Changes in Codebase

Option 2 - More like Sudo

If for some weird reason this is not running your commands as an Administrator you can try the runas command. Microsoft: runas command

Examples
  • runas /user:Administrator myCommand
  • runas "/user:First Last" "my command"
Notes
  • Just don't forget to put double quotes around anything that has a space in it.
  • Also it's quite possible that you have never set the password on the Administrator account, as it will ask you for the password when trying to run the command. You can always use an account without the username of Administrator if it has administrator access rights/permissions.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

General sibling combinator

The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.

More info

Reverting to a previous revision using TortoiseSVN

I have used the same instructions Stefan used, taken from Tortoise website.

But it's important to click COMMIT right after. I was getting crazy until I realized that.

If you need to make an older revision your head revision do the following:

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

  3. Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

  4. Make a commit.

org.hibernate.MappingException: Unknown entity

use below line of code in the case of spring boot applications.

@EntityScan(basePackageClasses=YourClassName.class)

Get element inside element by class and ID - JavaScript

THe easiest way to do so is:

function findChild(idOfElement, idOfChild){
  let element = document.getElementById(idOfElement);
  return element.querySelector('[id=' + idOfChild + ']');
}

or better readable:

findChild = (idOfElement, idOfChild) => {
    let element = document.getElementById(idOfElement);
    return element.querySelector(`[id=${idOfChild}]`);
}