Programs & Examples On #Ttlauncherview

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

How to get Current Directory?

WCHAR path[MAX_PATH] = {0};
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);

What is the use of GO in SQL Server Management Studio & Transact SQL?

Just to add to the existing answers, when you are creating views you must separate these commands into batches using go, otherwise you will get the error 'CREATE VIEW' must be the only statement in the batch. So, for example, you won't be able to execute the following sql script without go

create view MyView1 as
select Id,Name from table1
go
create view MyView2 as
select Id,Name from table1
go

select * from MyView1
select * from MyView2

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

Matching special characters and letters in regex

Add them to the allowed characters, but you'll need to escape some of them, such as -]/\

var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/

That way you can remove any individual character you want to disallow.

Also, you want to include the start and end of string placemarkers ^ and $

Update:

As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._

/^[\w&.\-]+$/

[\w] is the same as [a-zA-Z0-9_]

Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:

/^[\w&.\-]*$/

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The problem is that the true y is binary (zeros and ones), while your predictions are not. You probably generated probabilities and not predictions, hence the result :) Try instead to generate class membership, and it should work!

Passing by reference in C

You're not passing an int by reference, you're passing a pointer-to-an-int by value. Different syntax, same meaning.

CSS selector for a checked radio button's label

UPDATE:

This only worked for me because our existing generated html was wacky, generating labels along with radios and giving them both checked attribute.

Never mind, and big ups for Brilliand for bringing it up!

If your label is a sibling of a checkbox (which is usually the case), you can use the ~ sibling selector, and a label[for=your_checkbox_id] to address it... or give the label an id if you have multiple labels (like in this example where I use labels for buttons)


Came here looking for the same - but ended up finding my answer in the docs.

a label element with checked attribute can be selected like so:

label[checked] {
  ...
}

I know it's an old question, but maybe it helps someone out there :)

Differences between socket.io and websockets

tl;dr;

Comparing them is like comparing Restaurant food (maybe expensive sometimes, and maybe not 100% you want it) with homemade food, where you have to gather and grow each one of the ingredients on your own.

Maybe if you just want to eat an apple, the latter is better. But if you want something complicated and you're alone, it's really not worth cooking and making all the ingredients by yourself.


I've worked with both of these. Here is my experience.

SocketIO

  • Has autoconnect

  • Has namespaces

  • Has rooms

  • Has subscriptions service

  • Has a pre-designed protocol of communication

    (talking about the protocol to subscribe, unsubscribe or send a message to a specific room, you must all design them yourself in websockets)

  • Has good logging support

  • Has integration with services such as redis

  • Has fallback in case WS is not supported (well, it's more and more rare circumstance though)

  • It's a library. Which means, it's actually helping your cause in every way. Websockets is a protocol, not a library, which SocketIO uses anyway.

  • The whole architecture is supported and designed by someone who is not you, thus you dont have to spend time designing and implementing anything from the above, but you can go straight to coding business rules.

  • Has a community because it's a library (you can't have a community for HTTP or Websockets :P They're just standards/protocols)

Websockets

  • You have the absolute control, depending on who you are, this can be very good or very bad
  • It's as light as it gets (remember, its a protocol, not a library)
  • You design your own architecture & protocol
  • Has no autoconnect, you implement it yourself if yo want it
  • Has no subscription service, you design it
  • Has no logging, you implement it
  • Has no fallback support
  • Has no rooms, or namespaces. If you want such concepts, you implement them yourself
  • Has no support for anything, you will be the one who implements everything
  • You first have to focus on the technical parts and designing everything that comes and goes from and to your Websockets
  • You have to debug your designs first, and this is going to take you a long time

Obviously, you can see I'm biased to SocketIO. I would love to say so, but I'm really really not.

I'm really fighting not to use SocketIO. I dont wanna use it. I like designing my own stuff and solving my own problems myself. But if you want to have a business and not just a 1000 lines project, and you're going to choose Websockets, you're going to have to implement every single thing yourself. You have to debug everything. You have to make your own subscription service. Your own protocol. Your own everything. And you have to make sure everything is quite sophisticated. And you'll make A LOT of mistakes along the way. You'll spend tons of time designing and debugging everything. I did and still do. I'm using websockets and the reason I'm here is because they're unbearable for a one guy trying to deal with solving business rules for his startup and instead dealing with Websocket designing jargon.

Choosing Websockets for a big application ain't an easy option if you're a one guy army or a small team. I've wrote more code in Websockets than I ever wrote with SocketIO in the past, and all I have to say is ... Choose SocketIO if you want a finished product and design. (unless you want something very simple in functionality)

How can I escape a double quote inside double quotes?

Add "\" before double quote to escape it, instead of \

#! /bin/csh -f

set dbtable = balabala

set dbload = "load data local infile "\""'gfpoint.csv'"\"" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"\""' LINES TERMINATED BY "\""'\n'"\"" IGNORE 1 LINES"

echo $dbload
# load data local infile "'gfpoint.csv'" into table balabala FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "''" IGNORE 1 LINES

Easiest way to change font and font size

Maybe something like this:

yourformName.YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

Or if you are in the same class as the form then simply do this:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

The constructor takes diffrent parameters (so pick your poison). Like this:

Font(Font, FontStyle)   
Font(FontFamily, Single)
Font(String, Single)
Font(FontFamily, Single, FontStyle)
Font(FontFamily, Single, GraphicsUnit)
Font(String, Single, FontStyle)
Font(String, Single, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit)
Font(String, Single, FontStyle, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)
Font(String, Single, FontStyle, GraphicsUnit, Byte)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Reference here

C compiler for Windows?

You can use GCC on Windows by downloading MingW (discontinued) or its successor Mingw-w64.

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Remove leading comma from a string

var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.

linux script to kill java process

pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.

After an afternoon of swearing I went for putting the following in my start script:

(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true

How to use a PHP class from another file?

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

filtering NSArray into a new NSArray in Objective-C

NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.

NSMutableArray *array =
    [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];

NSPredicate *bPredicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
    [array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.

NSPredicate *sPredicate =
    [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filteredArrayUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }

How to force table cell <td> content to wrap?

This is another way of tackling the problem if you have long strings (like file path names) and you only want to break the strings on certain characters (like slashes). You can insert Unicode Zero Width Space characters just before (or after) the slashes in the HTML.

How exactly does the python any() function work?

It's because the iterable is

(x > 0 for x in list)

Note that x > 0 returns either True or False and thus you have an iterable of booleans.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try this (ES5)

console.log($("#" +  d));

ES6

console.log($(`#${d}`));

pass JSON to HTTP POST Request

According to doc: https://github.com/request/request

The example is:

  multipart: {
      chunked: false,
      data: [
        {
          'content-type': 'application/json', 
          body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
        },
      ]
    }

I think you send an object where a string is expected, replace

body: requestData

by

body: JSON.stringify(requestData)

UL list style not applying

All I can think of is that something is over-riding this afterwards.

You are including the reset styles first, right?

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Why is 1/1/1970 the "epoch time"?

History.

The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Remove file extension from a file name string

String.LastIndexOf would work.

string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
 fileName= fileName.Substring(0, fileExtPos);

Can someone explain the dollar sign in Javascript?

In your example the $ has no special significance other than being a character of the name.

However, in ECMAScript 6 (ES6) the $ may represent a Template Literal

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.

Is there a naming convention for git repositories?

I'd go for purchase-rest-service. Reasons:

  1. What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."

  2. "_" is harder to type than "-"

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

c++ string array initialization

Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:

string* pStr = new string[3] { "hi", "there"};

See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init

No connection could be made because the target machine actively refused it?

Go to your WCF project - properties -> Web -> debuggers -> unmark the checkbox

Enable Edit and Continue

How to make matrices in Python?

If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:

  mat = [[input() for i in range (col)] for j in range (row)]

and then enter the values you want.

Angular 2 Routing run in new tab

In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:

<button (click)="navigateToResource()">Navigate</button>

And in my component.ts

navigateToResource(): void {
  this.service.getUrl((result: any) => window.open(result.url));
}


Note:

Routing to a link indirectly like this will likely trigger the browser's popup blocker.

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

SSH library for Java

Take a look at the very recently released SSHD, which is based on the Apache MINA project.

What is the difference between Python and IPython?

IPython is a powerful interactive Python interpreter that is more interactive comparing to the standard interpreter.

To get the standard Python interpreter you type python and you will get the >>> prompt from where you can work.

To get IPython interpreter, you need to install it first. pip install ipython. You type ipython and you get In [1]: as a prompt and you get In [2]: for the next command. You can call history to check the list of previous commands, and write %recall 1 to recall the command.

Even you are in Python you can run shell commands directly like !ping www.google.com. Looks like a command line Jupiter notebook if you used that before.

You can use [Tab] to autocomplete as shown in the image. enter image description here

Copying from one text file to another using Python

f=open('list1.txt')  
f1=open('output.txt','a')
for x in f.readlines():
    f1.write(x)
f.close()
f1.close()

this will work 100% try this once

Switching between GCC and Clang/LLVM using CMake

System wide C change on Ubuntu:

sudo update-alternatives --config cc

System wide C++ change on Ubuntu:

sudo update-alternatives --config c++

For each of the above, press Selection number (1) and Enter to select Clang:

  Selection    Path            Priority   Status
------------------------------------------------------------
* 0            /usr/bin/gcc     20        auto mode
  1            /usr/bin/clang   10        manual mode
  2            /usr/bin/gcc     20        manual mode
Press enter to keep the current choice[*], or type selection number:

Call child component method from parent class - Angular

This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child'; 
    @Component({ 
               selector: 'parent-app', 
               template: `<child-cmp></child-cmp>` 
              }) 
    export class parentComponent implements OnInit{ 
        @ViewChild(ChildComponent ) child: ChildComponent ; 

        ngOnInit() { 
           this.child.ChildTestCmp(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` 
})
export class ChildComponent {
  test: string;
  ChildTestCmp() 
  { 
    this.test = "I am child component!"; 
  }
 }

Register 32 bit COM DLL to 64 bit Windows 7

If problem not resolved, when using SysWoW64 version of regsvr32, make sure all library dependencies have same archetecture. For example, when

regsvr32 lib_x86.dll fails to register library, and %SystemRoot%\SysWow64\regsvr32 lib_x86 also fails, try to load lib_x86 to Dependency Walker application to see whole list of dependencies. If any item have 64-bit archetecture, here is the reason, why regsvr32 fails to load 32-bit library.

How to hide a button programmatically?

public void OnClick(View.v)
Button b1 = (Button) findViewById(R.id.playButton);
b1.setVisiblity(View.INVISIBLE);

Validate SSL certificates with Python

From release version 2.7.9/3.4.3 on, Python by default attempts to perform certificate validation.

This has been proposed in PEP 467, which is worth a read: https://www.python.org/dev/peps/pep-0476/

The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).

Relevant documentation:

https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection

Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

Note that the new built-in verification is based on the system-provided certificate database. Opposed to that, the requests package ships its own certificate bundle. Pros and cons of both approaches are discussed in the Trust database section of PEP 476.

Transport security has blocked a cleartext HTTP

Here are the settings visually:

visual settings for NSAllowsArbitraryLoads in info.plist via Xcode GUI

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

Eclipse doesn't stop at breakpoints

I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

How can I specify a branch/tag when adding a Git submodule?

The only effect of choosing a branch for a submodule is that, whenever you pass the --remote option in the git submodule update command line, Git will check out in detached HEAD mode (if the default --checkout behavior is selected) the latest commit of that selected remote branch.

You must be particularly careful when using this remote branch tracking feature for Git submodules if you work with shallow clones of submodules. The branch you choose for this purpose in submodule settings IS NOT the one that will be cloned during git submodule update --remote. If you pass also the --depth parameter and you do not instruct Git about which branch you want to clone -- and actually you cannot in the git submodule update command line!! -- , it will implicitly behave like explained in the git-clone(1) documentation for git clone --single-branch when the explicit --branch parameter is missing, and therefore it will clone the primary branch only.

With no surprise, after the clone stage performed by the git submodule update command, it will finally try to check out the latest commit for the remote branch you previously set up for the submodule, and, if this is not the primary one, it is not part of your local shallow clone, and therefore it will fail with

fatal: Needed a single revision

Unable to find current origin/NotThePrimaryBranch revision in submodule path 'mySubmodule'

Inserting line breaks into PDF

Your code reads

$pdf->InsertText('Line one\n\nLine two');

I don't know about the PDF library you're using but normally if you want \n to be interpreted as a line break you must use double quotes in PHP, e.g.

$pdf->InsertText("Line one\n\nLine two");

How can I get CMake to find my alternative Boost installation?

I had a similar issue, and I could use customized Boost libraries by adding the below lines to my CMakeLists.txt file:

set(Boost_NO_SYSTEM_PATHS TRUE)
if (Boost_NO_SYSTEM_PATHS)
  set(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../3p/boost")
  set(BOOST_INCLUDE_DIRS "${BOOST_ROOT}/include")
  set(BOOST_LIBRARY_DIRS "${BOOST_ROOT}/lib")
endif (Boost_NO_SYSTEM_PATHS)
find_package(Boost REQUIRED regex date_time system filesystem thread graph program_options)
include_directories(${BOOST_INCLUDE_DIRS})

Change the "From:" address in Unix "mail"

On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:

...
11.22.33.44 localhost default-domain whatever-else.com
...

To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:

...
11.22.33.44 whatever-else.com localhost default-domain
...

I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I still found that with the solutions above, it didn't work (for example) with the Rails plugin for TextMate. I got a similar error (when retrieving the database schema).

So what did is, open terminal:

cd /usr/local/lib
sudo ln -s ../mysql-5.5.8-osx10.6-x86_64/lib/libmysqlclient.16.dylib .

Replace mysql-5.5.8-osx10.6-x86_64 with your own path (or mysql).

This makes a symbol link to the lib, now rails runs from the command line, as-well as TextMate plugin(s) like ruby-on-rails-tmbundle.

To be clear: this also fixes the error you get when starting rails server.

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Where should I put <script> tags in HTML markup?

It makes more sense to me to include the script after the HTML. Because most of the time I need the Dom to load before I execute my script. I could put it in the head tag but I don't like all the Document loading listener overhead. I want my code to be short and sweet and easy to read.

I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares. I don't know anybody using that old crap do you.

Good question by the way.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

include antiforgerytoken in ajax post ASP.NET MVC



        function DeletePersonel(id) {

                var data = new FormData();
                data.append("__RequestVerificationToken", "@HtmlHelper.GetAntiForgeryToken()");

                $.ajax({
                    type: 'POST',
                    url: '/Personel/Delete/' + id,
                    data: data,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (result) {

                    }
                });

        }
    

        public static class HtmlHelper
        {
            public static string GetAntiForgeryToken()
            {
                System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=\")(.*)(?:\")");
                if (value.Success)
                {
                    return value.Groups[1].Value;
                }
                return "";
            }
        }

How to convert CSV file to multiline JSON?

Use pandas and the json library:

import pandas as pd
import json
filepath = "inputfile.csv"
output_path = "outputfile.json"

df = pd.read_csv(filepath)

# Create a multiline json
json_list = json.loads(df.to_json(orient = "records"))

with open(output_path, 'w') as f:
    for item in json_list:
        f.write("%s\n" % item)

res.sendFile absolute path

process.cwd() returns the absolute path of your project.

Then :

res.sendFile( `${process.cwd()}/public/index1.html` );

ffprobe or avprobe not found. Please install one

I know the user asked this for Linux, but I had this issue in Windows (10 64bits) and found little information, so this is how I solved it:

  • Download LIBAV, I used libav-11.3-win64.7z. Just copy "avprobe.exe" and all DLLs from "/win64/usr/bin" to where "youtube-dl.exe" is.

In case LIBAV does not help, try with FFMPEG, copying the contents of the "bin" folder to where "youtube-dl.exe" is. That did not help me, but others said it did, so it may worth a try.

Hope this helps someone having the issue in Windows.

Why can't I check if a 'DateTime' is 'Nothing'?

You can also use below just simple to check:

If startDate <> Nothing Then
your logic
End If

It will check that the startDate variable of DateTime datatype is null or not.

ImportError: numpy.core.multiarray failed to import

Tilde folders

In the event pip uninstall numpy and reinstallation of Numpy does not work. Review your site-packages folder for sub-folders beginning with a tilde ~

These folders relate to pip installations that got mangled and the installation was aborted part way through. The tilde folders were only ever meant to be tmp folders but ended up becoming permanent. In my case there was a file called ~mpy which was a mangled legacy Numpy folder. This led to compatibility issues and ImportErrors.

These mangled folders can safely be deleted, for further details see this answer

Delete all data in SQL Server database

Usually I will just use the undocumented proc sp_MSForEachTable

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' 
GO 

-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 
GO

See also: Delete all data in database (when you have FKs)

How can I determine if a .NET assembly was built for x86 or x64?

How about you just write you own? The core of the PE architecture hasn't been seriously changed since its implementation in Windows 95. Here's a C# example:

    public static ushort GetPEArchitecture(string pFilePath)
    {
        ushort architecture = 0;
        try
        {
            using (System.IO.FileStream fStream = new System.IO.FileStream(pFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream))
                {
                    if (bReader.ReadUInt16() == 23117) //check the MZ signature
                    {
                        fStream.Seek(0x3A, System.IO.SeekOrigin.Current); //seek to e_lfanew.
                        fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); //seek to the start of the NT header.
                        if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature.
                        {
                            fStream.Seek(20, System.IO.SeekOrigin.Current); //seek past the file header,
                            architecture = bReader.ReadUInt16(); //read the magic number of the optional header.
                        }
                    }
                }
            }
        }
        catch (Exception) { /* TODO: Any exception handling you want to do, personally I just take 0 as a sign of failure */}
        //if architecture returns 0, there has been an error.
        return architecture;
    }
}

Now the current constants are:

0x10B - PE32  format.
0x20B - PE32+ format.

But with this method it allows for the possibilities of new constants, just validate the return as you see fit.

SQL Server: Filter output of sp_who2

This is the solution for you: http://blogs.technet.com/b/wardpond/archive/2005/08/01/the-openrowset-trick-accessing-stored-procedure-output-in-a-select-statement.aspx

select * from openrowset ('SQLOLEDB', '192.168.x.x\DATA'; 'user'; 'password', 'sp_who') 

git: 'credential-cache' is not a git command

For the sake of others who come on this issue, I had this same problem in Ubuntu (namely that my passwords weren't caching, despite having set the option correctly, and getting the error git: 'credential-cache' is not a git command.), until I found out that this feature is only available in Git 1.7.9 and above.

Being on an older distribution of Ubuntu (Natty; I'm a stubborn Gnome 2 user) the version in the repo was git version 1.7.4.1. I used the following PPA to upgrade: https://launchpad.net/~git-core/+archive/ppa

Test method is inconclusive: Test wasn't run. Error?

In my case, ReSharper gave me this additional exception in the test window:

2017.06.15 12:56:57.621   ERROR Exploration failed with the exception:
System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at JetBrains.ReSharper.UnitTestFramework.Launch.Stages.DiscoveryStage.Run(CancellationToken token)
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

it ended up that the test projects giving this error both were not set to build at all in the Configuration Manager. Checking the checkbox to build the 2 test projects and rebuilding sorted for me.

enter image description here

Referencing system.management.automation.dll in Visual Studio

The assembly coming with Powershell SDK (C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0) does not come with Powershell 2 specific types.

Manually editing the csproj file solved my problem.

scroll up and down a div on button click using jquery

scrollBottom is not a method in jQuery.

UPDATED DEMO - http://jsfiddle.net/xEFq5/10/

Try this:

   $("#upClick").on("click" ,function(){
     scrolled=scrolled-300;
        $(".cover").animate({
          scrollTop:  scrolled
     });
   });

How to support placeholder attribute in IE8 and 9

Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.

function fix_placeholder(container){
    if(container == null) container = document.body;

    if(!('placeholder' in document.createElement('input'))){

        var inputs = container.getElements('input');
        Array.each(inputs, function(input){

            var type = input.get('type');

            if(type == 'text' || type == 'password'){

                var placeholder = input.get('placeholder');
                input.set('value', placeholder);
                input.addClass('__placeholder');

                if(!input.hasEvent('focus', placeholder_focus)){
                    input.addEvent('focus', placeholder_focus);
                }

                if(!input.hasEvent('blur', placeholder_blur)){
                    input.addEvent('blur', placeholder_blur);
                }

            }

        });

    }
}

function placeholder_focus(){

    var input = $(this);    

    if(input.get('class').contains('__placeholder') || input.get('value') == ''){
        input.removeClass('__placeholder');
        input.set('value', '');
    }

}

function placeholder_blur(){

    var input = $(this);    

    if(input.get('value') == ''){
        input.addClass('__placeholder');
        input.set('value', input.get('placeholder'));
    }

}

I confess that it looks a bit more MORE than others but it works fine. __placeholder is a ccs-class to make the color of the placeholder text fancy.

I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.

Hope you like it.

Kind regards.

How to Save Console.WriteLine Output to Text File

do you want to write code for that or just use command-line feature 'command redirection' as follows:

app.exe >> output.txt

as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)

EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

Cannot create SSPI context

I had this error- it happened because my password expired and I had to change it. I didn't notice it, because in some programs I could still log in and everything would work normally (including windows), but I couldn't log to any sql servers.

Why should hash functions use a prime number modulus?

I would say the first answer at this link is the clearest answer I found regarding this question.

Consider the set of keys K = {0,1,...,100} and a hash table where the number of buckets is m = 12. Since 3 is a factor of 12, the keys that are multiples of 3 will be hashed to buckets that are multiples of 3:

  • Keys {0,12,24,36,...} will be hashed to bucket 0.
  • Keys {3,15,27,39,...} will be hashed to bucket 3.
  • Keys {6,18,30,42,...} will be hashed to bucket 6.
  • Keys {9,21,33,45,...} will be hashed to bucket 9.

If K is uniformly distributed (i.e., every key in K is equally likely to occur), then the choice of m is not so critical. But, what happens if K is not uniformly distributed? Imagine that the keys that are most likely to occur are the multiples of 3. In this case, all of the buckets that are not multiples of 3 will be empty with high probability (which is really bad in terms of hash table performance).

This situation is more common that it may seem. Imagine, for instance, that you are keeping track of objects based on where they are stored in memory. If your computer's word size is four bytes, then you will be hashing keys that are multiples of 4. Needless to say that choosing m to be a multiple of 4 would be a terrible choice: you would have 3m/4 buckets completely empty, and all of your keys colliding in the remaining m/4 buckets.

In general:

Every key in K that shares a common factor with the number of buckets m will be hashed to a bucket that is a multiple of this factor.

Therefore, to minimize collisions, it is important to reduce the number of common factors between m and the elements of K. How can this be achieved? By choosing m to be a number that has very few factors: a prime number.

FROM THE ANSWER BY Mario.

CSS:Defining Styles for input elements inside a div

Like this.

.divContainer input[type="text"] {
  width:150px;
}
.divContainer input[type="radio"] {
  width:20px;
}

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

For me didn't work the recognized solution from this post: https://stackoverflow.com/a/9619478/4507034.

Instead, I managed to solve the problem by importing the certification to my machine trusted certifications.

Steps:

  1. Go to the URL (eg. https://localhost:8443/yourpath) where the certification is not working.
  2. Export the certification as described in the mentioned post.
  3. On your windows machine open: Manage computer certificates
  4. Go to Trusted Root Certification Authorities -> Certificates
  5. Import here your your_certification_name.cer file.

Print array elements on separate lines in Bash?

Just quote the argument to echo:

( IFS=$'\n'; echo "${my_array[*]}" )

the sub shell helps restoring the IFS after use

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

Xcode source automatic formatting

I suggest using ClangFormat. In order to install, please follow these steps:

  1. Install Alcatraz package manager for XCode Supports Xcode 5+ & OS X 10.9+
  2. After installation restart XCode.
  3. Open XCode -> Window Menu -> Package Manager
  4. Search (find) ClangFormat and install it. After installation again restart XCode.
  5. Now at XCode menu you can use Edit -> Clang Format submenu for formatting.

You can choose different types of formatting. Also by enabling Format On Save you can gain auto-format capability.

enter image description here

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

How can I convert a string to boolean in JavaScript?

You need to separate (in your thinking) the value of your selections and the representation of that value.

Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)

In other words, yes, you need to depend on the string's value. :-)

Execute multiple command lines with the same process using .NET

A command-line process such cmd.exe or mysql.exe will usually read (and execute) whatever you (the user) type in (at the keyboard).

To mimic that, I think you want to use the RedirectStandardInput property: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx

How to find the socket connection state in C?

I had a similar problem. I wanted to know whether the server is connected to client or the client is connected to server. In such circumstances the return value of the recv function can come in handy. If the socket is not connected it will return 0 bytes. Thus using this I broke the loop and did not have to use any extra threads of functions. You might also use this same if experts feel this is the correct method.

How do you cast a List of supertypes to a List of subtypes?

The problem is that your method does NOT return a list of TestA if it contains a TestB, so what if it was correctly typed? Then this cast:

class TestA{};
class TestB extends TestA{};
List<? extends TestA> listA;
List<TestB> listB = (List<TestB>) listA;

works about as well as you could hope for (Eclipse warns you of an unchecked cast which is exactly what you are doing, so meh). So can you use this to solve your problem? Actually you can because of this:

List<TestA> badlist = null; // Actually contains TestBs, as specified
List<? extends TestA> talist = badlist;  // Umm, works
List<TextB> tblist = (List<TestB>)talist; // TADA!

Exactly what you asked for, right? or to be really exact:

List<TestB> tblist = (List<TestB>)(List<? extends TestA>) badlist;

seems to compile just fine for me.

How to solve maven 2.6 resource plugin dependency?

Seems your settings.xml file is missing your .m2 (local maven repo) folder.

When using eclipse navigate to Window -> Preferences -> Maven -> User Settings -> Browse to your settings.xml and click apply.

Then do maven Update Project.

enter image description here

How to use SSH to run a local shell script on a remote machine?

This is an extension to YarekT's answer to combine inline remote commands with passing ENV variables from the local machine to the remote host so you can parameterize your scripts on the remote side:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'
  # commands to run on remote host
  echo $ARG1 $ARG2
ENDSSH

I found this exceptionally helpful by keeping it all in one script so it's very readable and maintainable.

Why this works. ssh supports the following syntax:

ssh user@host remote_command

In bash we can specify environment variables to define prior to running a command on a single line like so:

ENV_VAR_1='value1' ENV_VAR_2='value2' bash -c 'echo $ENV_VAR_1 $ENV_VAR_2'

That makes it easy to define variables prior to running a command. In this case echo is our command we're running. Everything before echo defines environment variables.

So we combine those two features and YarekT's answer to get:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'...

In this case we are setting ARG1 and ARG2 to local values. Sending everything after user@host as the remote_command. When the remote machine executes the command ARG1 and ARG2 are set the local values, thanks to local command line evaluation, which defines environment variables on the remote server, then executes the bash -s command using those variables. Voila.

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

I had a similar issue and my solution was this code snippet (tested in IE8/9, Chrome and Firefox)

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

iframe.src = 'javascript:void((function(){var script = document.createElement(\'script\');' +
  'script.innerHTML = "(function() {' +
  'document.open();document.domain=\'' + document.domain +
  '\';document.close();})();";' +
  'document.write("<head>" + script.outerHTML + "</head><body></body>");})())';

iframe.contentWindow.document.write('<div>foo</div>');

I've tried several methods but this one appeared to be the best. You can find some explanations in my blog post here.

Python: Finding differences between elements of a list

>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])]  # or use itertools.izip in py2k
[2, 3]

How to append something to an array?

You can use push and apply function to append two arrays.

_x000D_
_x000D_
var array1 = [11, 32, 75];_x000D_
var array2 = [99, 67, 34];_x000D_
_x000D_
Array.prototype.push.apply(array1, array2);_x000D_
console.log(array1);
_x000D_
_x000D_
_x000D_

It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34]. This code is much simpler than writing for loops to copy each and every items in the array.

Vertical Menu in Bootstrap

Try the following (no custom.css required):

<div class="col-md-2">
    <nav>
        <ul class="nav">
            <li><a href="#">Link1</a></li>
            <li><a href="#">Link2</a></li>
            <li><a href="#">Link3</a></li>
            <li><a href="#">Link4</a></li>
        </ul>
    </nav>
</div>

Large Numbers in Java

Use the BigInteger class that is a part of the Java library.

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html

Download a specific tag with Git

I do this is via the github API:

curl -H "Authorization: token %(access_token)s" -sL -o /tmp/repo.tar.gz "http://api.github.com/repos/%(organisation)s/%(repo)s/tarball/%(tag)s" ;\
tar xfz /tmp/repo.tar.gz -C /tmp/repo --strip-components=1 ; \

Converting 'ArrayList<String> to 'String[]' in Java

In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:

List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)

from java.base's java.util.Collection.toArray().

How to initialize an array in Java?

Syntax

 Datatype[] variable = new Datatype[] { value1,value2.... }

 Datatype variable[]  = new Datatype[] { value1,value2.... }

Example :

int [] points = new int[]{ 1,2,3,4 };

Passing a variable from one php include file to another: global vs. not

This is all you have to do:

In front.inc

global $name;
$name = 'james';

Python unexpected EOF while parsing

I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:

try :
 ....

since python was searching for a

except Exception as e:
 ....

but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Ignore files that have already been committed to a Git repository

Yes - .gitignore system only ignores files not currently under version control from git.

I.e. if you've already added a file called test.txt using git-add, then adding test.txt to .gitignore will still cause changes to test.txt to be tracked.

You would have to git rm test.txt first and commit that change. Only then will changes to test.txt be ignored.

Mask for an Input to allow phone numbers?

you can use cleave.js

// phone (123) 123-4567
var cleavePhone = new Cleave('.input-phone', {
        //prefix: '(123)',
        delimiters: ['(',') ','-'],
        blocks: [0, 3, 3, 4]
});

demo: https://jsfiddle.net/emirM/a8fogse1/

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

Creating a class object in c++

First of all, both cases calls a constructor. If you write

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it.

If you write

Example example;

The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.

As for the singleton question, you must simple invoke your static method by writing:

Example *e = Singleton::getExample();

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How to check String in response body with mockMvc

One possible approach is to simply include gson dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

and parse the value to make your verifications:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private HelloService helloService;

    @Before
    public void before() {
        Mockito.when(helloService.message()).thenReturn("hello world!");
    }

    @Test
    public void testMessage() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                .andReturn();

        String responseBody = mvcResult.getResponse().getContentAsString();
        ResponseDto responseDto
                = new Gson().fromJson(responseBody, ResponseDto.class);
        Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
    }
}

How do I prevent and/or handle a StackOverflowException?

I would suggest creating a wrapper around XmlWriter object, so it would count amount of calls to WriteStartElement/WriteEndElement, and if you limit amount of tags to some number (f.e. 100), you would be able to throw a different exception, for example - InvalidOperation.

That should solve the problem in the majority of the cases

public class LimitedDepthXmlWriter : XmlWriter
{
    private readonly XmlWriter _innerWriter;
    private readonly int _maxDepth;
    private int _depth;

    public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100)
    {
    }

    public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth)
    {
        _maxDepth = maxDepth;
        _innerWriter = innerWriter;
    }

    public override void Close()
    {
        _innerWriter.Close();
    }

    public override void Flush()
    {
        _innerWriter.Flush();
    }

    public override string LookupPrefix(string ns)
    {
        return _innerWriter.LookupPrefix(ns);
    }

    public override void WriteBase64(byte[] buffer, int index, int count)
    {
        _innerWriter.WriteBase64(buffer, index, count);
    }

    public override void WriteCData(string text)
    {
        _innerWriter.WriteCData(text);
    }

    public override void WriteCharEntity(char ch)
    {
        _innerWriter.WriteCharEntity(ch);
    }

    public override void WriteChars(char[] buffer, int index, int count)
    {
        _innerWriter.WriteChars(buffer, index, count);
    }

    public override void WriteComment(string text)
    {
        _innerWriter.WriteComment(text);
    }

    public override void WriteDocType(string name, string pubid, string sysid, string subset)
    {
        _innerWriter.WriteDocType(name, pubid, sysid, subset);
    }

    public override void WriteEndAttribute()
    {
        _innerWriter.WriteEndAttribute();
    }

    public override void WriteEndDocument()
    {
        _innerWriter.WriteEndDocument();
    }

    public override void WriteEndElement()
    {
        _depth--;

        _innerWriter.WriteEndElement();
    }

    public override void WriteEntityRef(string name)
    {
        _innerWriter.WriteEntityRef(name);
    }

    public override void WriteFullEndElement()
    {
        _innerWriter.WriteFullEndElement();
    }

    public override void WriteProcessingInstruction(string name, string text)
    {
        _innerWriter.WriteProcessingInstruction(name, text);
    }

    public override void WriteRaw(string data)
    {
        _innerWriter.WriteRaw(data);
    }

    public override void WriteRaw(char[] buffer, int index, int count)
    {
        _innerWriter.WriteRaw(buffer, index, count);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        _innerWriter.WriteStartAttribute(prefix, localName, ns);
    }

    public override void WriteStartDocument(bool standalone)
    {
        _innerWriter.WriteStartDocument(standalone);
    }

    public override void WriteStartDocument()
    {
        _innerWriter.WriteStartDocument();
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        if (_depth++ > _maxDepth) ThrowException();

        _innerWriter.WriteStartElement(prefix, localName, ns);
    }

    public override WriteState WriteState
    {
        get { return _innerWriter.WriteState; }
    }

    public override void WriteString(string text)
    {
        _innerWriter.WriteString(text);
    }

    public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    {
        _innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
    }

    public override void WriteWhitespace(string ws)
    {
        _innerWriter.WriteWhitespace(ws);
    }

    private void ThrowException()
    {
        throw new InvalidOperationException(string.Format("Result xml has more than {0} nested tags. It is possible that xslt transformation contains an endless recursive call.", _maxDepth));
    }
}

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

This should be called a warning, not an error. At least the email says that the icon file is "recommended" and not "required". You can safely ignore this warning if you target iOS 6. Of course, for iOS 7 you would need the new dimensions and also look out for the new rounding of the icon's corners

Comparing Class Types in Java

Try this:

MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true

Because of inheritance this is valid for interfaces, too:

class Animal {}
class Dog extends Animal {}    

Dog obj = new Dog();
Animal animal = new Dog();
if(obj instanceof Animal){System.out.println("true");} //true
if(animal instanceof Animal){System.out.println("true");} //true
if(animal instanceof Dog){System.out.println("true");} //true

For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

How to send a "multipart/form-data" with requests in python?

Send multipart/form-data key and value

curl command:

curl -X PUT http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F taskStatus=1

python requests - More complicated POST requests:

    updateTaskUrl = "http://127.0.0.1:8080/api/xxx"
    updateInfoDict = {
        "taskStatus": 1,
    }
    resp = requests.put(updateTaskUrl, data=updateInfoDict)

Send multipart/form-data file

curl command:

curl -X POST http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F file=@/Users/xxx.txt

python requests - POST a Multipart-Encoded File:

    filePath = "/Users/xxx.txt"
    fileFp = open(filePath, 'rb')
    fileInfoDict = {
        "file": fileFp,
    }
    resp = requests.post(uploadResultUrl, files=fileInfoDict)

that's all.

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

How to select the last record of a table in SQL?

$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

How to create custom button in Android using XML Styles

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

   <solid 
       android:color="#ffffffff"/>

   <size 
       android:width="@dimen/shape_circle_width"
        android:height="@dimen/shape_circle_height"/>
</shape>

1.add this in your drawable

2.set as background to your button

How to do a num_rows() on COUNT query in codeigniter?

I'd suggest instead of doing another query with the same parameters just immediately running a SELECT FOUND_ROWS()

convert strtotime to date time format in php

Here is exp.

$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);

Upload DOC or PDF using PHP

One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files

Form Submission without page refresh

The problem is the Method 'POST' your form is submitting by using the "post" method, and in the AJAX you are using "GET".

Can Windows Containers be hosted on linux?

We can run Linux containers on Windows. Docker for Windows uses Hyper-v based Linux-Kit or WSL2 as backend to facilitate Linux containers.

If any Linux distribution having this kind of setup, we can run Windows containers. Docker for Linux supports only Linux containers.

How to change ProgressBar's progress indicator color in Android

I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:

<ProgressBar
    android:id="@+id/ProgressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:indeterminate="false"
    android:maxHeight="10dip"
    android:minHeight="10dip"
    android:progress="50"
    android:progressDrawable="@drawable/greenprogress" />

Then create a new drawable with something similar to the following (In this case greenprogress.xml):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                android:angle="270"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:startColor="#ff9d9e9d" />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                    android:angle="270"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:startColor="#80ffd300" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                    android:angle="270"
                    android:endColor="#008000"
                    android:startColor="#33FF33" />
            </shape>
        </clip>
    </item>

</layer-list>

You can change up the colors as needed, this will give you a green progress bar.

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

how to write an array to a file Java

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
    Files.write( // write to file
        Paths.get(fileName), // get path from file
        Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
        Charset.forName("UTF-8") // formatting
    );
}

How do I return the SQL data types from my query?

select * from information_schema.columns

could get you started.

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

javascript setTimeout() not working

To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously

setTimeout(function(){
      startTimer();
      function2();
      function3();
}, startInterval);

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

Curiously, I was able to solve the same issue by doing the exact opposite move to svc's ! I had to :

1) replace the FQDN hostname in my tnsnames.ora / listener.ora files with localhost, and restart the listener service, and

2) two, I had to use "SYS as SYSDBA" as the username in the SQL Developer input textbox

to finally be able to have SQL Developer hook to my local instance.

How to get a random value from dictionary?

To select 50 random key values from a dictionary set dict_data:

sample = random.sample(set(dict_data.keys()), 50)

How can I kill whatever process is using port 8080 so that I can vagrant up?

Run: nmap -p 8080 localhost (Install nmap with MacPorts or Homebrew if you don't have it on your system yet)

Nmap scan report for localhost (127.0.0.1)

Host is up (0.00034s latency).

Other addresses for localhost (not scanned): ::1

PORT STATE SERVICE

8080/tcp open http-proxy

Run: ps -ef | grep http-proxy

UID PID PPID C STIME TTY TIME CMD

640 99335 88310 0 12:26pm ttys002 0:00.01 grep http-proxy"

Run: ps -ef 640 (replace 501 with your UID)

/System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/XPCServices/com.apple.PerformanceAnalysis.animationperfd.xpc/Contents/MacOS/com.apple.PerformanceAnalysis.animationperfd

Port 8080 on mac osx is used by something installed with XCode SDK

adb command for getting ip address assigned by operator

To get all IPs (WIFI and data SIM) even on a non-rooted phone in 2019 use:

adb shell ip -o a

The output looks like:

1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever
1: lo    inet6 ::1/128 scope host \       valid_lft forever preferred_lft forever
3: dummy0    inet6 fe80::489c:2ff:fe4a:00005/64 scope link \       valid_lft forever preferred_lft forever
11: rmnet_data1    inet6 fe80::735d:50fb:2e2:0000/64 scope link \       valid_lft forever preferred_lft forever
21: r_rmnet_data0    inet6 fe80::e38:ce2a:523a:0000/64 scope link \       valid_lft forever preferred_lft forever
30: wlan0    inet 192.168.178.0/24 brd 192.168.178.255 scope global wlan0\       valid_lft forever preferred_lft forever
30: wlan0    inet6 fe80::c2ee:fbff:fe4a:0000/64 scope link \       valid_lft forever preferred_lft forever

You can connect either through adb shell or run the comman ip -o a directly in a terminal emulator. Again, no root required.

Server did not recognize the value of HTTP Header SOAPAction

I had same problem, it fixed after some checking:

<< Target WebService Exists but called method's not eXXXists. >>

my local service contain methods but target server(connecting server) does not contain specified called method.

Check your program scenario again...

Take the content of a list and append it to another list

You can simply concatnate two lists, e.g:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Best way to store a key=>value array in JavaScript?

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

What operator is <> in VBA

in sql... we use it for "not equals"... I am guessing, its the same in VB aswell.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

Disable dragging an image from an HTML page

just add draggable="false" to your image tag:

<img draggable="false" src="image.png">

IE8 and under doesn't support however.

iterating and filtering two lists using java 8

list1 = list1.stream().filter(str1-> 
        list2.stream().map(x->x.getStr()).collect(Collectors.toSet())
        .contains(str1)).collect(Collectors.toList());

This may work more efficient.

JSchException: Algorithm negotiation fail

Finally a solution that works without having to make any changes to the server:

  1. Download the latest jsch.jar as Yvan suggests: http://sourceforge.net/projects/jsch/files/jsch.jar/ jsch-0.1.52.jar works fine

  2. Place the downloaded file in your "...\JetBrains\PhpStorm 8.0.1\lib", and remove the existing jsch-file (for PHPStorm 8 it's jsch-0.1.50.jar)

  3. Restart PHPStorm and it should work

Use the same solution for Webstorm

What is the difference between class and instance methods?

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

Load a WPF BitmapImage from a System.Drawing.Bitmap

The easiest thing is if you can make the WPF bitmap from a file directly.

Otherwise you will have to use System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap.

Encrypt and Decrypt in Java

Here is a sample I made a couple of months ago The class encrypt and decrypt data

import java.security.*;
import java.security.spec.*;

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class TestEncryptDecrypt {

private final String ALGO = "DES";
private final String MODE = "ECB";
private final String PADDING = "PKCS5Padding";
private static int mode = 0;

public static void main(String args[]) {
    TestEncryptDecrypt me = new TestEncryptDecrypt();
    if(args.length == 0) mode = 2;
    else mode = Integer.parseInt(args[0]);
    switch (mode) {
    case 0:
        me.encrypt();
        break;
    case 1:
        me.decrypt();
        break;
    default:
        me.encrypt();
        me.decrypt();
    }
}

public void encrypt() {
try {
    System.out.println("Start encryption ...");

    /* Get Input Data */
    String input = getInputData();
    System.out.println("Input data : "+input);

    /* Create Secret Key */
    KeyGenerator keyGen = KeyGenerator.getInstance(ALGO);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.init(56,random);
      Key sharedKey = keyGen.generateKey();

    /* Create the Cipher and init it with the secret key */
    Cipher c = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING);
    //System.out.println("\n" + c.getProvider().getInfo());
    c.init(Cipher.ENCRYPT_MODE,sharedKey);
    byte[] ciphertext = c.doFinal(input.getBytes());
    System.out.println("Input Encrypted : "+new String(ciphertext,"UTF8"));

    /* Save key to a file */
    save(sharedKey.getEncoded(),"shared.key");

    /* Save encrypted data to a file */
    save(ciphertext,"encrypted.txt");
} catch (Exception e) {
    e.printStackTrace();
}   
}

public void decrypt() {
try {
    System.out.println("Start decryption ...");

    /* Get encoded shared key from file*/
    byte[] encoded = load("shared.key");
      SecretKeyFactory kf = SecretKeyFactory.getInstance(ALGO);
    KeySpec ks = new DESKeySpec(encoded);
    SecretKey ky = kf.generateSecret(ks);

    /* Get encoded data */
    byte[] ciphertext = load("encrypted.txt");
    System.out.println("Encoded data = " + new String(ciphertext,"UTF8"));

    /* Create a Cipher object and initialize it with the secret key */
    Cipher c = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING);
    c.init(Cipher.DECRYPT_MODE,ky);

    /* Update and decrypt */
    byte[] plainText = c.doFinal(ciphertext);
    System.out.println("Plain Text : "+new String(plainText,"UTF8"));
} catch (Exception e) {
    e.printStackTrace();
}   
}

private String getInputData() {
    String id = "owner.id=...";
    String name = "owner.name=...";
    String contact = "owner.contact=...";
    String tel = "owner.tel=...";
    final String rc = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();
    buf.append(id);
    buf.append(rc);
    buf.append(name);
    buf.append(rc);
    buf.append(contact);
    buf.append(rc);
    buf.append(tel);
    return buf.toString();
}


private void save(byte[] buf, String file) throws IOException {
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(buf);
      fos.close();
}

private byte[] load(String file) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(file);
    byte[] buf = new byte[fis.available()];
    fis.read(buf);
    fis.close();
    return buf;
}
}

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

How to make inline functions in C#

Yes, C# supports that. There are several syntaxes available.

  • Anonymous methods were added in C# 2.0:

    Func<int, int, int> add = delegate(int x, int y)
    {
        return x + y;
    };
    Action<int> print = delegate(int x)
    {
        Console.WriteLine(x);
    }
    Action<int> helloWorld = delegate // parameters can be elided if ignored
    {
        Console.WriteLine("Hello world!");
    }
    
  • Lambdas are new in C# 3.0 and come in two flavours.

    • Expression lambdas:

      Func<int, int, int> add = (int x, int y) => x + y; // or...
      Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
      
    • Statement lambdas:

      Action<int> print = (int x) => { Console.WriteLine(x); };
      Action<int> print = x => { Console.WriteLine(x); }; // inferred types
      Func<int, int, int> add = (x, y) => { return x + y; };
      
  • Local functions have been introduced with C# 7.0:

    int add(int x, int y) => x + y;
    void print(int x) { Console.WriteLine(x); }
    

There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>, which is roughly equivalent to Func<T, T, int>.

Func<string, string, int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l, r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards

These can be invoked directly as if they were regular methods:

int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
               // even though it does not make any use of it.

How to loop through each and every row, column and cells in a GridView and get its value

The easiest would be using a foreach:

foreach(GridViewRow row in GridView2.Rows)
{
    // here you'll get all rows with RowType=DataRow
    // others like Header are omitted in a foreach
}

Edit: According to your edits, you are accessing the column incorrectly, you should start with 0:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

How to increase timeout for a single test case in mocha

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.

Python conditional assignment operator

I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError. (see here, that Python has "names", not variables...).

== EDIT ==

As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

Nevertheless, if your variable "exists", but has some sort of dummy value, like None, the following would work :

>>> my_possibly_None_value = None
>>> myval = my_possibly_None_value or 5
>>> myval
5
>>> my_possibly_None_value = 12
>>> myval = my_possibly_None_value or 5
>>> myval
12
>>> 

(see this paragraph about Truth Values)

How to vertically align an image inside a div

This code work well for me.

<style>
    .listing_container{width:300px; height:300px;font: 0/0 a;}
    .listing_container:before { content: ' ';display: inline-block;vertical-align: bottom;height: 100%;}
    .listing_container img{ display: inline-block; vertical-align: middle;font: 16px/1 Arial sans-serif; max-height:100%; max-width:100%;}
<style>

<div class="listing_container">
    <img src="http://www.advancewebsites.com/img/theme1/logo.png">
</div>

Request Permission for Camera and Library in iOS 10 - Info.plist

You can also request for access programmatically, which I prefer because in most cases you need to know if you took the access or not.

Swift 4 update:

    //Camera
    AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
        if response {
            //access granted
        } else {

        }
    }

    //Photos
    let photos = PHPhotoLibrary.authorizationStatus()
    if photos == .notDetermined {
        PHPhotoLibrary.requestAuthorization({status in
            if status == .authorized{
                ...
            } else {}
        })
    }

You do not share code so I cannot be sure if this would be useful for you, but general speaking use it as a best practice.

What is the PostgreSQL equivalent for ISNULL()

Use COALESCE() instead:

SELECT COALESCE(Field,'Empty') from Table;

It functions much like ISNULL, although provides more functionality. Coalesce will return the first non null value in the list. Thus:

SELECT COALESCE(null, null, 5); 

returns 5, while

SELECT COALESCE(null, 2, 5);

returns 2

Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.

c# open a new form then close the current form?

This code may help you:

Master frm = new Master();

this.Hide();

frm.ShowDialog();

this.Close();

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.

function getDataUrl(file, callback2) {
        var callback = function (srcOrientation) {
            var reader2 = new FileReader();
            reader2.onload = function (e) {
                var srcBase64 = e.target.result;
                var img = new Image();

                img.onload = function () {
                    var width = img.width,
                        height = img.height,
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext("2d");

                    // set proper canvas dimensions before transform & export
                    if (4 < srcOrientation && srcOrientation < 9) {
                        canvas.width = height;
                        canvas.height = width;
                    } else {
                        canvas.width = width;
                        canvas.height = height;
                    }

                    // transform context before drawing image
                    switch (srcOrientation) {
                        case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
                        case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
                        case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
                        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
                        case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
                        case 7: ctx.transform(0, -1, -1, 0, height, width); break;
                        case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
                        default: break;
                    }

                    // draw image
                    ctx.drawImage(img, 0, 0);

                    // export base64
                    callback2(canvas.toDataURL());
                };

                img.src = srcBase64;
            }

            reader2.readAsDataURL(file);
        }

        var reader = new FileReader();
        reader.onload = function (e) {

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

which can easily be called like such

getDataUrl(input.files[0], function (imgBase64) {
      vm.user.BioPhoto = imgBase64;
});

JavaScript Infinitely Looping slideshow with delays?

You are calling setTimeout() ten times in a row, so they all expire almost at the same time. What you actually want is this:

window.onload = function start() {
    slide(10);
}
function slide(repeats) {
    if (repeats > 0) {
        document.getElementById('container').style.marginLeft='-600px';
        document.getElementById('container').style.marginLeft='-1200px';
        document.getElementById('container').style.marginLeft='-1800px';
        document.getElementById('container').style.marginLeft='0px';
        window.setTimeout(
          function(){
            slide(repeats - 1)
          },
          3000
        );
    }
}

This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

Returning a boolean from a Bash function

myfun(){
    [ -d "$1" ]
}
if myfun "path"; then
    echo yes
fi
# or
myfun "path" && echo yes

Debugging JavaScript in IE7

It's not a full debugger, but my DP_DEBUG extensions provides some (I think) usful functionality and they work in IE, Firefox and Opera (9+).

You can "dump" visual representations of complex JavaScript objects (even system objects), do simplified logging and timing. The component provides simple methods to enable or disable it so that you can leave the debugger in place for production work if you like.

DP_Debug

What's the equivalent of Java's Thread.sleep() in JavaScript?

For Best solution, Use async/await statement for ecma script 2017

await can use only inside of async function

function sleep(time) {
    return new Promise((resolve) => {
        setTimeout(resolve, time || 1000);
    });
}

await sleep(10000); //this method wait for 10 sec.

Note : async / await not actualy stoped thread like Thread.sleep but simulate it

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

This seems to be an Eclipse bug, though restarting Eclipse worked great for me, hope this helps somebody else too.

Magento: Set LIMIT on collection

The way to do was looking at the code in code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php at line 380 in Magento 1.7.2 on the function setPage($pageNum, $pageSize)

 $collection = Mage::getModel('model')
     ->getCollection()
     ->setCurPage(2) // 2nd page
     ->setPageSize(10); // 10 elements per pages

I hope this will help someone.

Check if a string is not NULL or EMPTY

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

Laravel Request::all() Should Not Be Called Statically

The facade is another Request class, access it with the full path:

$input = \Request::all();

From laravel 5 you can also access it through the request() function:

$input = request()->all();

Check if object value exists within a Javascript array of objects and if not add a new object to array

Here is an ES6 method chain using .map() and .includes():

const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

const checkForUser = (newUsername) => {
      arr.map(user => {
        return user.username
      }).includes(newUsername)
    }

if (!checkForUser('fred')){
  // add fred
}
  1. Map over existing users to create array of username strings.
  2. Check if that array of usernames includes the new username
  3. If it's not present, add the new user

Viewing localhost website from mobile device

To view localhost website from mobile device you have to follow thoses steps :

  • In your computer, you have to retrieve your IP address (Run > cmd > ipconfig)
  • If your localhost use a specific port (like localhost:12345 ), you have to open the port on your computer (Control Panel > System and Security > Firewall > Advanced settings and add Inbound rule)
  • Finally, you can access to your website from mobile device by navigate to : http://192.168.X.X:12345/

Hope it helps

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

How to loop and render elements in React.js without an array of objects to map?

Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

Passing struct to function

Instead of:

void addStudent(person)
{
    return;
}

try this:

void addStudent(student person)
{
    return;
}

Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:

void addStudent(struct student person)
{
    return;
}

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

Make copy of an array

you can use

int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();

as well.

Get the element triggering an onclick event in jquery?

It's top google stackoverflow question, but all answers are not jQuery related!

$(".someclass").click(
    function(event)
    {
        console.log(event, this);
    }
);

'event' contains 2 important values:

event.currentTarget - element to which event is triggered ('.someclass' element)

event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

How to pass parameters to $http in angularjs?

We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.

<input type="text" placeholder="Enter your Email" ng-model="email" required>

<input type="text" placeholder="Enter your password " ng-model="password" required> 

and in the js file w use $scope to access this data:

$scope.email="";
$scope.password="";

Controller function will be something like that:

 var app = angular.module('myApp', []);

    app.controller('assignController', function($scope, $http) {
      $scope.email="";
      $scope.password="";

      $http({
        method: "POST",
        url: "http://localhost:3000/users/sign_in",
        params: {email: $scope.email, password: $scope.password}

      }).then(function mySuccess(response) {
          // a string, or an object, carrying the response from the server.
          $scope.myRes = response.data;
          $scope.statuscode = response.status;

        }, function myError(response) {
          $scope.myRes = response.statusText;
      });
    });

HTTP Error 500.19 and error code : 0x80070021

In our case, we struggled with this error for quite some days. It turns out that in control panel, programs, turn windows features on or off.

We selected Internet Information Services, world wide web services, Application development features and there we check the set of features associated with our development environment. For example: ASP.NET 4.6. .NET Extensibility 4.6, etc.

It works!

Upload video files via PHP and save them in appropriate folder and have a database entry

sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>

ListAGG in SQLSERVER

Starting in SQL Server 2017 the STRING_AGG function is available which simplifies the logic considerably:

select FieldA, string_agg(FieldB, '') as data
from yourtable
group by FieldA

See SQL Fiddle with Demo

In SQL Server you can use FOR XML PATH to get the result:

select distinct t1.FieldA,
  STUFF((SELECT distinct '' + t2.FieldB
         from yourtable t2
         where t1.FieldA = t2.FieldA
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') data
from yourtable t1;

See SQL Fiddle with Demo

Loop X number of times

See this link. It shows you how to dynamically create variables in PowerShell.

Here is the basic idea:

Use New-Variable and Get-Variable,

for ($i=1; $i -le 5; $i++)
{
    New-Variable -Name "var$i" -Value $i
    Get-Variable -Name "var$i" -ValueOnly
}

(It is taken from the link provided, and I don't take credit for the code.)

Capture key press without placing an input element on the page?

For modern JS, use event.key!

document.addEventListener("keypress", function onPress(event) {
    if (event.key === "z" && event.ctrlKey) {
        // Do something awesome
    }
});

NOTE: The old properties (.keyCode and .which) are Deprecated.

Mozilla Docs

Supported Browsers

Getting value from a cell from a gridview on RowDataBound event

Just use a loop to check your cell in a gridview for example:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

How to get an Instagram Access Token

If you're looking for instructions, check out this article post. And if you're using C# ASP.NET, have a look at this repo.

Remote Connections Mysql Ubuntu

To expose MySQL to anything other than localhost you will have to have the following line

For mysql version 5.6 and below

uncommented in /etc/mysql/my.cnf and assigned to your computers IP address and not loopback

For mysql version 5.7 and above

uncommented in /etc/mysql/mysql.conf.d/mysqld.cnf and assigned to your computers IP address and not loopback

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

Or add a bind-address = 0.0.0.0 if you don't want to specify the IP

Then stop and restart MySQL with the new my.cnf entry. Once running go to the terminal and enter the following command.

lsof -i -P | grep :3306

That should come back something like this with your actual IP in the xxx's

mysqld  1046  mysql  10u  IPv4  5203  0t0  TCP  xxx.xxx.xxx.xxx:3306 (LISTEN)

If the above statement returns correctly you will then be able to accept remote users. However for a remote user to connect with the correct priveleges you need to have that user created in both the localhost and '%' as in.

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then,

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';

and finally,

FLUSH PRIVILEGES; 
EXIT;

If you don't have the same user created as above, when you logon locally you may inherit base localhost privileges and have access issues. If you want to restrict the access myuser has then you would need to read up on the GRANT statement syntax HERE If you get through all this and still have issues post some additional error output and the my.cnf appropriate lines.

NOTE: If lsof does not return or is not found you can install it HERE based on your Linux distribution. You do not need lsof to make things work, but it is extremely handy when things are not working as expected.

UPDATE: If even after adding/changing the bind-address in my.cnf did not work, then go and change it in the place it was originally declared:

/etc/mysql/mariadb.conf.d/50-server.cnf

Get public/external IP address?

Best answer I found

To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.

The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.

 public static string GetIP()
 {
            string externalIP = "";
            externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
            externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                           .Matches(externalIP)[0].ToString();
            return externalIP;
 }

Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.

public static WebClient webclient = new WebClient();
public static string GetIP()
{
    string externalIP = "";
    externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
    externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                   .Matches(externalIP)[0].ToString();
    return externalIP;
}

Compare two different files line by line in python

Once the file object is iterated, it is exausted.

>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1

2

3

# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>

Use file.seek (or close/open the file) to rewind the file:

>>> f.seek(0)
>>> for line in f: print line
...
1

2

3

Best way to access a control on another form in Windows Forms?

Step 1:

string regno, exm, brd, cleg, strm, mrks, inyear;

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    string url;
    regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
    exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
    brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text;
    cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text;
    strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text;
    mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text;
    inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text;

    url = "academicinfo.aspx?regno=" + regno + ", " + exm + ", " + brd + ", " +
          cleg + ", " + strm + ", " + mrks + ", " + inyear;
    Response.Redirect(url);
}

Step 2:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string prm_string = Convert.ToString(Request.QueryString["regno"]);

        if (prm_string != null)
        {
            string[] words = prm_string.Split(',');
            txt_regno.Text = words[0];
            txt_board.Text = words[2];
            txt_college.Text = words[3];
        }
    }
}

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I have a fresh Windows 10 installed on my PC and tried this on the command line and it works like a charm:

npm config rm https-proxy

PHP: How do I display the contents of a textfile on my page?

if you just want to show the file itself:

header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Python print statement “Syntax Error: invalid syntax”

In Python 3, print is a function, you need to call it like print("hello world").

Array initializing in Scala

To initialize an array filled with zeros, you can use:

> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)

This is equivalent to Java's new byte[5].