Programs & Examples On #Lightbox

Lightbox, and the newer Lightbox 2, is a JavaScript application used to display large images using modal dialogs.

Changing image sizes proportionally using CSS?

If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.

  1. The image will not get cropped
  2. The aspect ratio will also remain the same.

HTML:

<div id="app">
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
</div>

CSS:

div#container {
    height: 200px;
    width: 200px;
    border: 1px solid black;
    margin: 4px;
}
img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
}

Using JQuery to open a popup window and print

You should put the print function in your view-details.php file and call it once the file is loaded, by either using

<body onload="window.print()"> 

or

$(document).ready(function () { 
  window.print(); 
});

TypeError: $(...).on is not a function

In my case this code solved my error :

(function (window, document, $) {
            'use strict';
             var $html = $('html');
             $('input[name="myiCheck"]').on('ifClicked', function (event) {
             alert("You clicked " + this.value);
             });
})(window, document, jQuery);

You don't should put your function inside $(document).ready

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

Align DIV to bottom of the page

It's a quick fix, I hope it helps.

<div id="content">
content...
</div>
<footer>
content footer...
</footer>

css:

#content{min-height: calc(100vh - 100px);}

100vh is 100% height of device and 100px is height of footer

If the content is higher than height of device, the footer will stay on bottom. And the content is shorter than height of device, the footer will stay on bottom of screen

How to compare only date components from DateTime in EF?

Without time than try like this:

TimeSpan ts = new TimeSpan(23, 59, 59);
toDate = toDate.Add(ts);
List<AuditLog> resultLogs = 
    _dbContext.AuditLogs
    .Where(al => al.Log_Date >= fromDate && al.Log_Date <= toDate)
    .ToList();
return resultLogs;

What is the point of the diamond operator (<>) in Java 7?

In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?

  1. No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.
  2. The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.

IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.

Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as

package 7 com.example;

could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.

How to access /storage/emulated/0/

Android recommends that you call Environment.getExternalStorageDirectory.getPath() instead of hardcoding /sdcard/ in path name. This returns the primary shared/external storage directory. So, if storage is emulated, this will return /storage/emulated/0. If you explore the device storage with a file explorer, the said directory will be /mnt/sdcard (confirmed on Xperia Z2 running Android 6).

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

How can I list all collections in the MongoDB shell?

On >=2.x, you can do

db.listCollections()

On 1.x you can do

db.getCollectionNames()

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I'v tried all of these solutions but the one that has worked for me is:

  1. run react-native upgrade
  2. open xcode
  3. run the application in xCode
  4. works fine!

How to set the environmental variable LD_LIBRARY_PATH in linux

  1. Go to the home folder and edit .profile
  2. Place the following line at the end

    export LD_LIBRARY_PATH=<your path>

  3. Save and Exit.

  4. Execute this command

    sudo ldconfig

CSS: How can I set image size relative to parent height?

Change your code:

a.image_container img {
    width: 100%;
}

To this:

a.image_container img {
    width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
    height: 100%;
}

http://jsfiddle.net/f9krj/5/

Timer for Python game

I use this function in my python programs. The input for the function is as example:
value = time.time()

def stopWatch(value):
    '''From seconds to Days;Hours:Minutes;Seconds'''

    valueD = (((value/365)/24)/60)
    Days = int (valueD)

    valueH = (valueD-Days)*365
    Hours = int(valueH)

    valueM = (valueH - Hours)*24
    Minutes = int(valueM)

    valueS = (valueM - Minutes)*60
    Seconds = int(valueS)


    print Days,";",Hours,":",Minutes,";",Seconds




start = time.time() # What in other posts is described is

***your code HERE***

end = time.time()         
stopWatch(end-start) #Use then my code

Sublime Text 3, convert spaces to tabs

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

How to initialize private static members in C++?

Also working in privateStatic.cpp file :

#include <iostream>

using namespace std;

class A
{
private:
  static int v;
};

int A::v = 10; // possible initializing

int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}

// g++ privateStatic.cpp -o privateStatic && ./privateStatic

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

how to get javaScript event source element?

Your html should be like this:

<button onclick="doSomething" id="id_button">action</button>

And renaming your input-paramter to event like this

function doSomething(event){
    var source = event.target || event.srcElement;
    console.log(source);
}

would solve your problem.

As a side note, I'd suggest taking a look at jQuery and unobtrusive javascript

Creating temporary files in Android

Do it in simple. According to documentation https://developer.android.com/training/data-storage/files

String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
        picFile = new File(ProfileActivity.this.getCacheDir(),imageName);

and delete it after usage

picFile.delete()

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Disable/Enable button in Excel/VBA

I'm using excel 2010 and below VBA code worked fine for a Form Button. It removes the assigned macro from the button and assign in next command.

To disable:

ActiveSheet.Shapes("Button Name").OnAction = Empty
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 16

To enable:

ActiveSheet.Shapes("Button Name").OnAction = ActiveWorkbook.Name & "!Macro function Name with _Click"
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 1

Pls note "ActiveWorkbook.Name" stays as it is. Do not insert workbook name instead of "Name".

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

SELECT only rows that contain only alphanumeric characters in MySQL

Try this code:

SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$'

This makes sure that all characters match.

Registering for Push Notifications in Xcode 8/Swift 3.0?

The answer from ast1 is very simple and useful. It works for me, thank you so much. I just want to poin it out here, so people who need this answer can find it easily. So, here is my code from registering local and remote (push) notification.

    //1. In Appdelegate: didFinishLaunchingWithOptions add these line of codes
    let mynotif = UNUserNotificationCenter.current()
    mynotif.requestAuthorization(options: [.alert, .sound, .badge]) {(granted, error) in }//register and ask user's permission for local notification

    //2. Add these functions at the bottom of your AppDelegate before the last "}"
    func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
        application.registerForRemoteNotifications()//register for push notif after users granted their permission for showing notification
}
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("Device Token: \(tokenString)")//print device token in debugger console
}
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")//print error in debugger console
}

Language Books/Tutorials for popular languages

Ruby

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Printing with "\t" (tabs) does not result in aligned columns

The length of the text that you are providing in each line is different, this is the problem, so if the second word is too long (see2.txt is long 8 char which corresponds to a single tab lenght) it prints out a tab which goes to the next tabulation point. One way to solve it is to programmatically add a pad to the f.getName() text so each text generated: see.txt or see2.txt has the same lenght (for example see.txt_ and see2.txt) so each tab automatically goes to the same tabulation point.

If you are developing with JDK 1.5 you can solve this using java.util.Formatter:

String format = "%-20s %5d\n";
System.out.format(format, "test", 1);
System.out.format(format, "test2", 20);
System.out.format(format, "test3", 5000);

this example will give you this print:

test                     1
test2                   20
test3                 5000

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

How to insert text into the textarea at the current cursor position?

A simple solution that work on firefox, chrome, opera, safari and edge but probably won't work on old IE browsers.

  var target = document.getElementById("mytextarea_id")

  if (target.setRangeText) {
     //if setRangeText function is supported by current browser
     target.setRangeText(data)
  } else {
    target.focus()
    document.execCommand('insertText', false /*no UI*/, data);
  }
}

setRangeText function allow you to replace current selection with the provided text or if no selection then insert the text at cursor position. It's only supported by firefox as far as I know.

For other browsers there is "insertText" command which only affect the html element currently focused and has same behavior as setRangeText

Inspired partially by this article

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How to get Activity's content view?

How about

View view = Activity.getCurrentFocus();

jQuery: Can I call delay() between addClass() and such?

AFAIK the delay method only works for numeric CSS modifications.

For other purposes JavaScript comes with a setTimeout method:

window.setTimeout(function(){$("#div").removeClass("error");}, 1000);

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I often encounter this problem on windows,the way I solved the problem is Service - Click PostgreSQL Database Server 8.3 - Click the second tab "log in" - choose the first line "the local system account".

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

What is the most accurate way to retrieve a user's correct IP address in PHP?

Here's a modified version if you use CloudFlare caching layer Services

function getIP()
{
    $fields = array('HTTP_X_FORWARDED_FOR',
                    'REMOTE_ADDR',
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_CLUSTER_CLIENT_IP');

    foreach($fields as $f)
    {
        $tries = $_SERVER[$f];
        if (empty($tries))
            continue;
        $tries = explode(',',$tries);
        foreach($tries as $try)
        {
            $r = filter_var($try,
                            FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 |
                            FILTER_FLAG_NO_PRIV_RANGE |
                            FILTER_FLAG_NO_RES_RANGE);

            if ($r !== false)
            {
                return $try;
            }
        }
    }
    return false;
}

How to change PHP version used by composer

Another possibility to make composer think you're using the correct version of PHP is to add to the config section of a composer.json file a platform option, like this:

"config": {
    "platform": {
        "php": "<ver>"
    }
},

Where <ver> is the PHP version of your choice.

Snippet from the docs:

Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.

Shell script to send email

Basically there's a program to accomplish that, called "mail". The subject of the email can be specified with a -s and a list of address with -t. You can write the text on your own with the echo command:

echo "This will go into the body of the mail." | mail -s "Hello world" [email protected]

or get it from other files too:

mail -s "Hello world" [email protected] < /home/calvin/application.log

mail doesn't support the sending of attachments, but Mutt does:

echo "Sending an attachment." | mutt -a file.zip -s "attachment" [email protected]

Note that Mutt's much more complete than mail. You can find better explanation here

PS: thanks to @slhck who pointed out that my previous answer was awful. ;)

Filter dataframe rows if value in column is in a set list of values

You can use query, i.e.:

b = df.query('a > 1 & a < 5')

blur() vs. onblur()

Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.

When is std::weak_ptr useful?

std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not. Instead, by letting a std::shared_ptr manage the data, and supplying std::weak_ptr to users of the data, the users can check validity of the data by calling expired() or lock().

You could not do this with std::shared_ptr alone, because all std::shared_ptr instances share the ownership of the data which is not removed before all instances of std::shared_ptr are removed. Here is an example of how to check for dangling pointer using lock():

#include <iostream>
#include <memory>

int main()
{
    // OLD, problem with dangling pointer
    // PROBLEM: ref will point to undefined data!

    int* ptr = new int(10);
    int* ref = ptr;
    delete ptr;

    // NEW
    // SOLUTION: check expired() or lock() to determine if pointer is valid

    // empty definition
    std::shared_ptr<int> sptr;

    // takes ownership of pointer
    sptr.reset(new int);
    *sptr = 10;

    // get pointer to data without taking ownership
    std::weak_ptr<int> weak1 = sptr;

    // deletes managed object, acquires new pointer
    sptr.reset(new int);
    *sptr = 5;

    // get pointer to new data without taking ownership
    std::weak_ptr<int> weak2 = sptr;

    // weak1 is expired!
    if(auto tmp = weak1.lock())
        std::cout << *tmp << '\n';
    else
        std::cout << "weak1 is expired\n";

    // weak2 points to new data (5)
    if(auto tmp = weak2.lock())
        std::cout << *tmp << '\n';
    else
        std::cout << "weak2 is expired\n";
}

Regex allow digits and a single dot

Try this

boxValue = boxValue.replace(/[^0-9\.]/g,"");

This Regular Expression will allow only digits and dots in the value of text box.

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

Delete .idea folder in your project which is hidden folder. Goto your project in the system and Click ctrl+H it will be visible then delete it. Now restart your android studio.I will resolve. Its working for me.

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

Resize UIImage by keeping Aspect ratio and width

Best answer Maverick 1st's correctly translated to Swift (working with latest swift 3):

func imageWithImage (sourceImage:UIImage, scaledToWidth: CGFloat) -> UIImage {
    let oldWidth = sourceImage.size.width
    let scaleFactor = scaledToWidth / oldWidth

    let newHeight = sourceImage.size.height * scaleFactor
    let newWidth = oldWidth * scaleFactor

    UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
    sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

Fixed page header overlaps in-page anchors

// handle hashes when page loads
// <http://stackoverflow.com/a/29853395>
function adjustAnchor() {
  const $anchor = $(':target');
  const fixedElementHeight = $('.navbar-fixed-top').outerHeight();
  if ($anchor.length > 0)
    window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
}
$(window).on('hashchange load', adjustAnchor);
$('body').on('click', "a[href^='#']", function (ev) {
  if (window.location.hash === $(this).attr('href')) {
    ev.preventDefault();
    adjustAnchor();
  }
});

How to avoid 'cannot read property of undefined' errors?

This is a common issue when working with deep or complex json object, so I try to avoid try/catch or embedding multiple checks which would make the code unreadable, I usually use this little piece of code in all my procect to do the job.

/* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
 * accepts array for property names: 
 *     getProperty(myObj,['aze','xyz'],{value: null}) 
 */
function getProperty(obj, props, defaultValue) {
    var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
    if(!isvoid(obj)){
        if(isvoid(props)) props = [];
        if(typeof props  === "string") props = props.trim().split(".");
        if(props.constructor === Array){
            res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
        }
    }
    return typeof res === "undefined" ? defaultValue: res;
}

How can I remove a style added with .css() function?

Try

document.body.style=''

_x000D_
_x000D_
$("body").css("background-color", 'red');

function clean() {
  document.body.style=''
}
_x000D_
body { background-color: yellow; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="clean()">Remove style</button>
_x000D_
_x000D_
_x000D_

INSERT INTO...SELECT for all MySQL columns

don't you need double () for the values bit? if not try this (although there must be a better way

insert into this_table_archive (id, field_1, field_2, field_3) 
values
((select id from this_table where entry_date < '2001-01-01'), 
((select field_1 from this_table where entry_date < '2001-01-01'), 
((select field_2 from this_table where entry_date < '2001-01-01'), 
((select field_3 from this_table where entry_date < '2001-01-01'));

how to set the query timeout from SQL connection string

See:- ConnectionStrings content on this subject. There is no default command timeout property.

Concatenating two std::vectors

Or you could use:

std::copy(source.begin(), source.end(), std::back_inserter(destination));

This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of std::back_inserter to convert from one type to the other.

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

getaddrinfo: nodename nor servname provided, or not known

I got the error while trying to develop while disconnected to the Internet. However, the website I was working on needs to be able to talk to some other websites, so it choked when it couldn't do so. Connecting to the internet fixed the error.

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

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

How permission can be checked at runtime without throwing SecurityException?

if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }
} 

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

Add params to given URL in Python

I liked Lukasz version, but since urllib and urllparse functions are somewhat awkward to use in this case, I think it's more straightforward to do something like this:

params = urllib.urlencode(params)

if urlparse.urlparse(url)[4]:
    print url + '&' + params
else:
    print url + '?' + params

Sum values from an array of key-value pairs in JavaScript

Or in ES6

values.reduce((a, b) => a + b),

example:

[1,2,3].reduce((a, b)=>a+b) // return 6

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

I have had the same error. I added dependency on pom.xml (I am working with Maven)

<dependency> 
        <groupId>com.fasterxml.jackson.core</groupId> 
        <artifactId>jackson-core</artifactId> 
        <version>2.12.1</version> 
 </dependency> 

I started trying with version 2.9.0, then I found a different error (com/fasterxml/jackson/core/exc/InputCoercionException) then I try different versions until all errors were solved with version 2.12.1

Update Git submodule to latest commit on origin

It seems like two different scenarios are being mixed together in this discussion:

Scenario 1

Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.

This is, as pointed out, done with

git submodule foreach git pull origin BRANCH
git submodule update

Scenario 2, which I think is what OP is aiming at

New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.

This would be done by

git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH

Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.

It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add) to point to the head of the submodule(s).

For this, I made this small Bash script:

git-update-submodules.sh

#!/bin/bash

APP_PATH=$1
shift

if [ -z $APP_PATH ]; then
  echo "Missing 1st argument: should be path to folder of a git repo";
  exit 1;
fi

BRANCH=$1
shift

if [ -z $BRANCH ]; then
  echo "Missing 2nd argument (branch name)";
  exit 1;
fi

echo "Working in: $APP_PATH"
cd $APP_PATH

git checkout $BRANCH && git pull --ff origin $BRANCH

git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH

To run it, execute

git-update-submodules.sh /path/to/base/repo BRANCH_NAME

Elaboration

First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.

The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).

git checkout $BRANCH && git pull --ff origin $BRANCH

Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:

git submodule sync
git submodule init
git submodule update

Then I update/pull all submodules:

git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

Notice a few things: First of all, I'm chaining some Git commands using && - meaning previous command must execute without error.

After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.

Finally, the final || true is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).

My favourite part:

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

Iterate all submodules - with --quiet, which removes the 'Entering MODULE_PATH' output. Using 'echo $path' (must be in single-quotes), the path to the submodule gets written to output.

This list of relative submodule paths is captured in an array ($(...)) - finally iterate this and do git add $i to update the parent repository.

Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.

I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.

I hope this will be of help to someone.

Find full path of the Python interpreter?

Just noting a different way of questionable usefulness, using os.environ:

import os
python_executable_path = os.environ['_']

e.g.

$ python -c "import os; print(os.environ['_'])"
/usr/bin/python

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

How to make a gap between two DIV within the same column

you can use $nbsp; for a single space, if you like just using single allows you single space instead of using creating own class

    <div id="bulkOptionContainer" class="col-xs-4">
        <select class="form-control" name="" id="">
            <option value="">Select Options</option>
            <option value="">Published</option>
            <option value="">Draft</option>
            <option value="">Delete</option>
        </select>
    </div>

    <div class="col-xs-4">

        <input type="submit" name="submit" class="btn btn-success " value="Apply">
         &nbsp;
        <a class="btn btn-primary" href="add_posts.php">Add post</a>

    </div>


</form>

CLICK ON IMAGE

Check for false

If you want to check for false and alert if not, then no there isn't.

If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.

Converting unix timestamp string to readable date

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

Output:

'December 26, 2012'

How to get current relative directory of your Makefile?

Here is one-liner to get absolute path to your Makefile file using shell syntax:

SHELL := /bin/bash
CWD := $(shell cd -P -- '$(shell dirname -- "$0")' && pwd -P)

And here is version without shell based on @0xff answer:

CWD := $(abspath $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))))

Test it by printing it, like:

cwd:
        @echo $(CWD)

Super-simple example of C# observer/observable with delegates

The observer pattern is usually implemented with events.

Here's an example:

using System;

class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething() =>
        SomethingHappened?.Invoke(this, EventArgs.Empty);
}

class Observer
{
    public void HandleEvent(object sender, EventArgs args)
    {
        Console.WriteLine("Something happened to " + sender);
    }
}

class Test
{
    static void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
    }
}

See the linked article for a lot more detail.

Note that the above example uses C# 6 null-conditional operator to implement DoSomething safely to handle cases where SomethingHappened has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:

public void DoSomething()
{
    var handler = SomethingHappened;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

Convert varchar to uniqueidentifier in SQL Server

DECLARE @uuid VARCHAR(50)
SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'
SELECT  CAST(
        SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
        SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
        AS UNIQUEIDENTIFIER)

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

How to initialise a string from NSData in Swift

This is how you should initialize the NSString:

Swift 2.X or older

let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)

Swift 3 or newer:

let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)

This doc explains the syntax.

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How to set a value for a selectize.js input?

Note setValue only works if there are already predefined set of values for the selectize control ( ex. select field ), for controls where the value could be dynamic ( ex. user can add values on the fly, textbox field ) setValue ain't gonna work.

Use createItem functon instead for adding and setting the current value of the selectize field

ex.

$selectize[ 0 ].selectize.clear(); // Clear existing entries
for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
    $selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown

Error during installing HAXM, VT-X not working

If your emulators were working and now they aren't due to Avast...

Avast no longer has the option for "Enable Hardware-assisted Virtualization" in Troubleshooting. (it's now March 2017)

Avast captures "emulator.exe", which disables emulators,and stows it in the Virus chest. Open the chest, "Restore and add to exclusions" and your emulator works again...

Pictorial on Avast fix

How to increment a pointer address and pointer's value?

        Note:
        1) Both ++ and * have same precedence(priority), so the associativity comes into picture.
        2) in this case Associativity is from **Right-Left**

        important table to remember in case of pointers and arrays: 

        operators           precedence        associativity

    1)  () , []                1               left-right
    2)  *  , identifier        2               right-left
    3)  <data type>            3               ----------

        let me give an example, this might help;

        char **str;
        str = (char **)malloc(sizeof(char*)*2); // allocate mem for 2 char*
        str[0]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char
        str[1]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char

        strcpy(str[0],"abcd");  // assigning value
        strcpy(str[1],"efgh");  // assigning value

        while(*str)
        {
            cout<<*str<<endl;   // printing the string
            *str++;             // incrementing the address(pointer)
                                // check above about the prcedence and associativity
        }
        free(str[0]);
        free(str[1]);
        free(str);

How to get a random number in Ruby

Don't forget to seed the RNG with srand() first.

Docker can't connect to docker daemon

With Docker installed with snap, I sometimes encounter the OP's error upon rebooting my machine. In my case, running sudo snap logs docker revealed an error in the logs:

Error starting daemon: pid file found, ensure docker is not running or delete /var/snap/docker/423/run/docker.pid

After running sudo rm /var/snap/docker/423/run/docker.pid, I can start Docker normally.

Create a File object in memory from a string in Java

The File class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File class has a .exists() method, to tell you if the file exists or not. (How can you have a File object that doesn't exist?)

By contrast, constructing a new FileInputStream(new File("/my/file")) gives you an actual stream to read bytes from.

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

What is lexical scope?

Lexical (AKA static) scoping refers to determining a variable's scope based solely on its position within the textual corpus of code. A variable always refers to its top-level environment. It's good to understand it in relation to dynamic scope.

Is there any difference between "!=" and "<>" in Oracle Sql?

Actually, there are four forms of this operator:

<>
!=
^=

and even

¬= -- worked on some obscure platforms in the dark ages

which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I agree that StringTokenizer is overkill here. Actually I tried out the suggestions above and took the time.

My test was fairly simple: create a StringBuilder with about a million characters, convert it to a String, and traverse each of them with charAt() / after converting to a char array / with a CharacterIterator a thousand times (of course making sure to do something on the string so the compiler can't optimize away the whole loop :-) ).

The result on my 2.6 GHz Powerbook (that's a mac :-) ) and JDK 1.5:

  • Test 1: charAt + String --> 3138msec
  • Test 2: String converted to array --> 9568msec
  • Test 3: StringBuilder charAt --> 3536msec
  • Test 4: CharacterIterator and String --> 12151msec

As the results are significantly different, the most straightforward way also seems to be the fastest one. Interestingly, charAt() of a StringBuilder seems to be slightly slower than the one of String.

BTW I suggest not to use CharacterIterator as I consider its abuse of the '\uFFFF' character as "end of iteration" a really awful hack. In big projects there's always two guys that use the same kind of hack for two different purposes and the code crashes really mysteriously.

Here's one of the tests:

    int count = 1000;
    ...

    System.out.println("Test 1: charAt + String");
    long t = System.currentTimeMillis();
    int sum=0;
    for (int i=0; i<count; i++) {
        int len = str.length();
        for (int j=0; j<len; j++) {
            if (str.charAt(j) == 'b')
                sum = sum + 1;
        }
    }
    t = System.currentTimeMillis()-t;
    System.out.println("result: "+ sum + " after " + t + "msec");

Can you nest html forms?

I ran into a similar problem, and I know that is not an answer to the question, but it can be of help to someone with this kind of problem:
if there is need to put the elements of two or more forms in a given sequence, the HTML5 <input> form attribute can be the solution.

From http://www.w3schools.com/tags/att_input_form.asp:

  1. The form attribute is new in HTML5.
  2. Specifies which <form> element an <input> element belongs to. The value of this attribute must be the id attribute of a <form> element in the same document.

Scenario:

  • input_Form1_n1
  • input_Form2_n1
  • input_Form1_n2
  • input_Form2_n2

Implementation:

<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>

<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />

<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />

Here you'll find browser's compatibility.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How to perform case-insensitive sorting in JavaScript?

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if( a == b) return 0;
    if( a > b) return 1;
    return -1;
});

In above function, if we just compare when lower case two value a and b, we will not have the pretty result.

Example, if array is [A, a, B, b, c, C, D, d, e, E] and we use the above function, we have exactly that array. It's not changed anything.

To have the result is [A, a, B, b, C, c, D, d, E, e], we should compare again when two lower case value is equal:

function caseInsensitiveComparator(valueA, valueB) {
    var valueALowerCase = valueA.toLowerCase();
    var valueBLowerCase = valueB.toLowerCase();

    if (valueALowerCase < valueBLowerCase) {
        return -1;
    } else if (valueALowerCase > valueBLowerCase) {
        return 1;
    } else { //valueALowerCase === valueBLowerCase
        if (valueA < valueB) {
            return -1;
        } else if (valueA > valueB) {
            return 1;
        } else {
            return 0;
        }
    }
}

Where can I set path to make.exe on Windows?

The path is in the registry but usually you edit through this interface:

  1. Go to Control Panel -> System -> System settings -> Environment Variables.
  2. Scroll down in system variables until you find PATH.
  3. Click edit and change accordingly.
  4. BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
  5. Launch a new console for the settings to take effect.

How to Rotate a UIImage 90 degrees?

If you want to add a photo rotate button that'll keep rotating the photo in 90 degree increments, here you go. (finalImage is a UIImage that's already been created elsewhere.)

- (void)rotatePhoto {
    UIImage *rotatedImage;

    if (finalImage.imageOrientation == UIImageOrientationRight)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationDown];
    else if (finalImage.imageOrientation == UIImageOrientationDown)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationLeft];
    else if (finalImage.imageOrientation == UIImageOrientationLeft)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationUp];
    else
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];
    finalImage = rotatedImage;
}

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.


The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints

sum(a) = 20

How do I correctly clone a JavaScript object?

To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a clone method to Object.prototype, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to Object.prototype, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with the hasOwnProperty method.

In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example, prototype is a hidden property of a function. Also, an object's prototype is referenced with the attribute __proto__, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think __proto__ might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically.

Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype is Object, then simply creating a new general object with {} will work, but if the source's prototype is some descendant of Object, then you are going to be missing the additional members from that prototype which you skipped using the hasOwnProperty filter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object's constructor property to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, a Date object stores its data as a hidden member:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

var d1 = new Date();

/* Executes function after 5 seconds. */
setTimeout(function(){
    var d2 = clone(d1);
    alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString());
}, 5000);

The date string for d1 will be 5 seconds behind that of d2. A way to make one Date the same as another is by calling the setTime method, but that is specific to the Date class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong!

When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plain Object, Array, Date, String, Number, or Boolean. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in Object or Array would also be one of the 6 simple types in that list. This can be accomplished with code like the following:

function clone(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:

// This would be cloneable:
var tree = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "right" : null,
    "data"  : 8
};

// This would kind-of work, but you would get 2 copies of the 
// inner node instead of 2 references to the same copy
var directedAcylicGraph = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "data"  : 8
};
directedAcyclicGraph["right"] = directedAcyclicGraph["left"];

// Cloning this would cause a stack overflow due to infinite recursion:
var cyclicGraph = {
    "left"  : { "left" : null, "right" : null, "data" : 3 },
    "data"  : 8
};
cyclicGraph["right"] = cyclicGraph;

It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.

Visually managing MongoDB documents and collections

The real answer is ... No.

So far as I have found there is no reasonable or publicly available Windows MonogoDB client which is really very sad since MongoDB is pretty sweet.

I've thought about throwing together a simple app with WPF on Codeplex ... but I haven't been super motivated.

What would features would you be interested in having? Maybe you can inspire me or others?

For example, do you just want to view DBs / collections & perhaps simple edits (so you don't have to use the shell) or do you require something more complex?

What is the difference between JOIN and UNION?

Remember that union will merge results (SQL Server to be sure)(feature or bug?)

select 1 as id, 3 as value
union
select 1 as id, 3 as value

id,value

1,3

select * from (select 1 as id, 3 as value) t1 inner join (select 1 as id, 3 as value) t2 on t1.id = t2.id

id,value,id,value

1,3,1,3

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

Jquery get input array field

I think the best way, is to use a Propper Form and to use jQuery.serializeArray.

<!-- a form with any type of input -->
<form class="a-form">
    <select name="field[something]">...</select>
    <input type="checkbox" name="field[somethingelse]" ... />
    <input type="radio" name="field[somethingelse2]" ... />
    <input type="text" name="field[somethingelse3]" ... />
</form>

<!-- sample ajax call -->
<script>
$(document).ready(function(){
    $.ajax({
        url: 'submit.php',
        type: 'post',
        data: $('form.a-form').serializeArray(),
        success: function(response){
            ...
        }
    });
});
</script>

The Values will be available in PHP as $_POST['field'][INDEX].

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

As Lambdageek pointed out float multiplication is not associative and you can get less accuracy, but also when get better accuracy you can argue against optimisation, because you want a deterministic application. For example in game simulation client/server, where every client has to simulate the same world you want floating point calculations to be deterministic.

C++, How to determine if a Windows Process is running?

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

/*!
\brief Check if a process is running
\param [in] processName Name of process to check if is running
\returns \c True if the process is running, or \c False if the process is not running
*/
bool IsProcessRunning(const wchar_t *processName)
{
    bool exists = false;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry))
        while (Process32Next(snapshot, &entry))
            if (!wcsicmp(entry.szExeFile, processName))
                exists = true;

    CloseHandle(snapshot);
    return exists;
}

Where does Anaconda Python install on Windows?

If you installed as admin ( and meant for all users )

C:\ProgramData\Anaconda3\Scripts\anaconda.exe

If you install as a normal user

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

jquery get all input from specific form

The below code helps to get the details of elements from the specific form with the form id,

$('#formId input, #formId select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements from all the forms which are place in the loading page,

$('form input, form select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,

$('input, select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

NOTE: We add the more element tag name what we need in the object list like as below,

Example: to get name of attribute "textarea",

$('input, select, textarea').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

How to replace unicode characters in string with something else python?

Encode string as unicode.

>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Possibly too late to be of benefit now, but is this not the easiest way to do things?

SELECT     empName, projIDs = replace
                          ((SELECT Surname AS [data()]
                              FROM project_members
                              WHERE  empName = a.empName
                              ORDER BY empName FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM         project_members a
WHERE     empName IS NOT NULL
GROUP BY empName

Check string length in PHP

The xpath() function does not return a string. It returns an array with XML elements (of type SimpleXMLElement), which may be casted to a string.

if (count($message)) {
   if (strlen((string)$message[0]) < 141) {
      echo "There Are No Contests.";
   }
   else if(strlen((string)$message[0]) > 142) {
      echo "There is One Active Contest.";
   }
}

Check if an element is present in a Bash array

1) Initialize array arr and add elements

2) set variable to search for SEARCH_STRING

3) check if your array contains element

arr=()
arr+=('a')
arr+=('b')
arr+=('c')

SEARCH_STRING='b'

if [[ " ${arr[*]} " == *"$SEARCH_STRING"* ]];
then
    echo "YES, your arr contains $SEARCH_STRING"
else
    echo "NO, your arr does not contain $SEARCH_STRING"
fi

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

Get value of div content using jquery

your div looks like this:

<div class="readonly_label" id="field-function_purpose">Other</div>

With jquery you can easily get inner content:

Use .html() : HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

var text = $('#field-function_purpose').html(); 

Read more about jquery .html()

or

Use .text() : Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

var text = $('#field-function_purpose').text();

Read more about jquery .text()

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Git Clone from GitHub over https with two-factor authentication

It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.

How to Authenticate Git using Access Tokens

  1. Go to https://github.com/settings/tokens
  2. Click Generate New Token button on top right.
  3. Give your token a descriptive name.
  4. Set all required permissions for the token.
  5. Click Generate token button at the bottom.
  6. Copy the generated token to a safe place.
  7. Use this token instead of password when you use git clone.

Wow, it works!

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try using the ASCII code for those values:

^([a-zA-Z0-9 .\x26\x27-]+)$
  • \x26 = &
  • \x27 = '

The format is \xnn where nn is the two-digit hexadecimal character code. You could also use \unnnn to specify a four-digit hex character code for the Unicode character.

WAMP shows error 'MSVCR100.dll' is missing when install

I encountered this problem when my operating system was in French, and I was installing Wampserver in English.

I am pretty sure that Microsoft Redistributable packages were installed since I was already working with Visual Studio. I think the issue may have been because of changes in path names with different languages. However, when I installed wampserver in French, everything worked perfectly.

The thread has exited with code 0 (0x0) with no unhandled exception

In order to complete BlueM's accepted answer, you can desactivate it here:

Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off

Send POST request with JSON data using Volley

  • Create an object of RequestQueue class.

    RequestQueue queue = Volley.newRequestQueue(this);
    
  • Create a StringRequest with response and error listener.

     StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            mPostCommentResponse.requestCompleted();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mPostCommentResponse.requestEndedWithError(error);
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("user",userAccount.getUsername());
            params.put("pass",userAccount.getPassword());
            params.put("comment", Uri.encode(comment));
            params.put("comment_post_ID",String.valueOf(postId));
            params.put("blogId",String.valueOf(blogId));
    
            return params;
        }
    
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    
  • Add your request into the RequestQueue.

    queue.add(jsObjRequest);
    
  • Create PostCommentResponseListener interface just so you can see it. It’s a simple delegate for the async request.

    public interface PostCommentResponseListener {
    public void requestStarted();
    public void requestCompleted();
    public void requestEndedWithError(VolleyError error);
    }
    
  • Include INTERNET permission inside AndroidManifest.xml file.

    <uses-permission android:name="android.permission.INTERNET"/>
    

Retrieve list of tasks in a queue in Celery

If you are using Celery+Django simplest way to inspect tasks using commands directly from your terminal in your virtual environment or using a full path to celery:

Doc: http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#inspecting-workers

$ celery inspect reserved
$ celery inspect active
$ celery inspect registered
$ celery inspect scheduled

Also if you are using Celery+RabbitMQ you can inspect the list of queues using the following command:

More info: https://linux.die.net/man/1/rabbitmqctl

$ sudo rabbitmqctl list_queues

Declare and initialize a Dictionary in Typescript

Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.

Record<string, Partial<IPerson>>

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: Record<string, Partial<IPerson>> = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};

Explanation.

  1. Record type creates a dictionary/hashmap.
  2. Partial type says some of the fields may be missing.

Alternate.

If you wish to make last name optional you can append a ? Typescript will know that it's optional.

lastName?: string;

https://www.typescriptlang.org/docs/handbook/utility-types.html

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Code:
Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

Embedding DLLs in a compiled executable

Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File… And include the code below to your App.xaml.cs or equivalent.

public App()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}

Here's my original blog post: http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/

SQLRecoverableException: I/O Exception: Connection reset

This simply means that something in the backend ( DBMS ) decided to stop working due to unavailability of resources etc. It has nothing to do with your code or the number of inserts. You can read more about similar problems here:

This may not answer your question, but you will get an idea of why it might be happening. You could further discuss with your DBA and see if there is something specific in your case.

Why doesn't Python have a sign function?

EDIT:

Indeed there was a patch which included sign() in math, but it wasn't accepted, because they didn't agree on what it should return in all the edge cases (+/-0, +/-nan, etc)

So they decided to implement only copysign, which (although more verbose) can be used to delegate to the end user the desired behavior for edge cases - which sometimes might require the call to cmp(x,0).


I don't know why it's not a built-in, but I have some thoughts.

copysign(x,y):
Return x with the sign of y.

Most importantly, copysign is a superset of sign! Calling copysign with x=1 is the same as a sign function. So you could just use copysign and forget about it.

>>> math.copysign(1, -4)
-1.0
>>> math.copysign(1, 3)
1.0

If you get sick of passing two whole arguments, you can implement sign this way, and it will still be compatible with the IEEE stuff mentioned by others:

>>> sign = functools.partial(math.copysign, 1) # either of these
>>> sign = lambda x: math.copysign(1, x) # two will work
>>> sign(-4)
-1.0
>>> sign(3)
1.0
>>> sign(0)
1.0
>>> sign(-0.0)
-1.0
>>> sign(float('nan'))
-1.0

Secondly, usually when you want the sign of something, you just end up multiplying it with another value. And of course that's basically what copysign does.

So, instead of:

s = sign(a)
b = b * s

You can just do:

b = copysign(b, a)

And yes, I'm surprised you've been using Python for 7 years and think cmp could be so easily removed and replaced by sign! Have you never implemented a class with a __cmp__ method? Have you never called cmp and specified a custom comparator function?

In summary, I've found myself wanting a sign function too, but copysign with the first argument being 1 will work just fine. I disagree that sign would be more useful than copysign, as I've shown that it's merely a subset of the same functionality.

JVM heap parameters

The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.

It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.

As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.

jQuery Ajax Request inside Ajax Request

Call second ajax from 'complete'

Here is the example

   var dt='';
   $.ajax({
    type: "post",
    url: "ajax/example.php",
    data: 'page='+btn_page,
    success: function(data){
        dt=data;
        /*Do something*/
    },
    complete:function(){
        $.ajax({
           var a=dt; // This line shows error.
           type: "post",
           url: "example.php",
           data: 'page='+a,
           success: function(data){
              /*do some thing in second function*/
           },
       });
    }
});

How to make a HTTP request using Ruby on Rails?

Here is the code that works if you are making a REST api call behind a proxy:

require "uri"
require 'net/http'

proxy_host = '<proxy addr>'
proxy_port = '<proxy_port>'
proxy_user = '<username>'
proxy_pass = '<password>'

uri = URI.parse("https://saucelabs.com:80/rest/v1/users/<username>")
proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)

req = Net::HTTP::Get.new(uri.path)
req.basic_auth(<sauce_username>,<sauce_password>)

result = proxy.start(uri.host,uri.port) do |http|
http.request(req)
end

puts result.body

Shell Script — Get all files modified after <date>

I would simply do the following to backup all new files from 7 days ago

tar --newer $(date -d'7 days ago' +"%d-%b") -zcf thisweek.tgz .

note you can also replace '7 days ago' with anything that suits your need

Can be : date -d'yesterday' +"%d-%b"

Or even : date -d'first Sunday last month' +"%d-%b"

batch file Copy files with certain extensions from multiple directories into one directory

Things like these are why I switched to Powershell. Try it out, it's fun:

Get-ChildItem -Recurse -Include *.doc | % {
    Copy-Item $_.FullName -destination x:\destination
}

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

How does String substring work in Swift

Came across this fairly short and simple way of achieving this.

var str = "Hello, World"
let arrStr = Array(str)
print(arrStr[0..<5]) //["H", "e", "l", "l", "o"]
print(arrStr[7..<12]) //["W", "o", "r", "l", "d"]
print(String(arrStr[0..<5])) //Hello
print(String(arrStr[7..<12])) //World

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

This linker error usually (in my experience) means that you've overridden a virtual function in a child class with a declaration, but haven't given a definition for the method. For example:

class Base
{
    virtual void f() = 0;
}
class Derived : public Base
{
    void f();
}

But you haven't given the definition of f. When you use the class, you get the linker error. Much like a normal linker error, it's because the compiler knew what you were talking about, but the linker couldn't find the definition. It's just got a very difficult to understand message.

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

How can I remove jenkins completely from linux

On Centos7, It is important to note that while you remove jenkins using following command: sudo yum remove jenkins

it will not remove your users and other information. For that you will have to do following: sudo rm -r /var/lib/jenkins

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

xcopy file, rename, suppress "Does xxx specify a file name..." message

There is some sort of undocumented feature in XCOPY. you can use:

xcopy "bin\development\whee.config.example" "c:\mybackup\TestConnectionExternal\bin\Debug\whee.config*"

i tested it just today. :-)

UIWebView open links in Safari

One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.

What you can do to prevent this (thanks Wade) is:

if (inType == UIWebViewNavigationTypeLinkClicked) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;

You might also want to handle the UIWebViewNavigationTypeFormSubmitted and UIWebViewNavigationTypeFormResubmitted types.

Why is it that "No HTTP resource was found that matches the request URI" here?

I had that problem, if you are calling your REST Methods from another Assembly you must be sure that all your references have the same version as your main project references, otherwise will never find your controllers.

Regards.

How to filter files when using scp to copy dir recursively?

I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:-

rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \ 
/usr/project/backup/some/unknown/number/of/sub/folders/

Some other useful flags:

  • -r for recursive
  • -a for archive (mostly all files)
  • -v for verbose output
  • -e to specify ssh instead of the default (which should be ssh, actually)

Get Image Height and Width as integer values?

getimagesize() returns an array containing the image properties.

list($width, $height) = getimagesize("path/to/image.jpg");

to just get the width and height or

list($width, $height, $type, $attr)

to get some more information.

Sublime Text 2 - View whitespace characters

If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces

Detect if the device is iPhone X

- (BOOL)isIphoneX {
    if (@available(iOS 11.0, *)) {
        UIWindow *window = UIApplication.sharedApplication.keyWindow;
        CGFloat topPadding = window.safeAreaInsets.top;
        if(topPadding>0) {
            return YES;
        }
        else {
            return NO;
        }
    }
    else {
        return NO;
    }
}

Shortcut for creating single item list in C#

You can also do

new List<string>() { "string here" };

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How do I pass a list as a parameter in a stored procedure?

Maybe you could use:

select last_name+', '+first_name 
from user_mstr
where ',' + @user_id_list + ',' like '%,' + convert(nvarchar, user_id) + ',%'

How to create <input type=“text”/> dynamically

You could use createElement() method for creating that textbox

Maven plugins can not be found in IntelliJ

For me, I download them manually and put theme in my .m2 folder then i did invalidate cache and restart (I m using Intellij IDEA). The steps are for example:

<groupId>org.codehaus.mojo</groupId>
              <artifactId>jdepend-maven-plugin</artifactId>
<version>2.0</version>
  1. I go to https://mvnrepository.com/ then serch for jdepend-maven-plugin choose the version 2.0
  2. In Files go and click on View All
  3. Download this files jdepend-maven-plugin-2.0.jar jdepend-maven-plugin-2.0.jar.sh1 jdepend-maven-plugin-2.0.pom jdepend-maven-plugin-2.0.pom.sh1
  4. go to .m2 folder then org/codehaus/mojo Create folder with name jdepend-maven-plugin inside with name 2.0 inside put the 4 files downloaded befor.

  5. create file with name _remote.repositories open it with text editor and write inside

jdepend-maven-plugin-2.0.jar>central=
jdepend-maven-plugin-2.0.pom>central=

  1. go to intellij IDEA invalidate cache and restart.

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

make sure ,use this 404 route wrote on the bottom of the code.

syntax will be like

{
    path: 'page-not-found', 
    component: PagenotfoundComponent
},
{
    path: '**', 
    redirectTo: '/page-not-found'
},

Thank you

How to increase the gap between text and underlining in CSS

Here is what works well for me.

_x000D_
_x000D_
<style type="text/css">_x000D_
  #underline-gap {_x000D_
    text-decoration: underline;_x000D_
    text-underline-position: under;_x000D_
  }_x000D_
</style>_x000D_
<body>_x000D_
  <h1 id="underline-gap"><a href="https://Google.com">Google</a></h1>_x000D_
</body>
_x000D_
_x000D_
_x000D_

jQuery set checkbox checked

Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.

I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.

Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":

if (allDay)
{
    $( "#even_allday_yn").prop('checked', true);
}
else
{
    $( "#even_allday_yn").prop('checked', false);
}

twitter bootstrap typeahead ajax example

I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.

<?php if (isset($_GET['typeahead'])){
    die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('index.php?typeahead', { query: query }, function (data) {
            return process(JSON.parse(data).options);
        });
    }
});
</script>

Declare and Initialize String Array in VBA

Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)

Then you can do something static like this:

myStringArray = { item_1, item_2, ... }

Or something iterative like this:

Dim x
For x = 0 To size_of_your_array
    myStringArray(x) = data_source(x).Name
Next x

UIScrollView scroll to bottom programmatically

With an (optional) footerView and contentInset, the solution is:

CGPoint bottomOffset = CGPointMake(0, _tableView.contentSize.height - tableView.frame.size.height + _tableView.contentInset.bottom);
if (bottomOffset.y > 0) [_tableView setContentOffset: bottomOffset animated: YES];

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

C++20 std::source_location

C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}

int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

__PRETTY_FUNCTION__ vs __FUNCTION__ vs __func__ vs std::source_location::function_name

Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Specify an SSH key for git push for a given domain

To use a specific key on the fly:

GIT_SSH_COMMAND='ssh -i $HOME/.ssh/id_ed25519 -o IdentitiesOnly=yes -F /dev/null' git push origin c13_training_network

Explanation:

  • local ENV var before doing the push
  • -i specifies key
  • -F forces an empty config so your global one doesn't overwrite this temporary command

T-SQL Cast versus Convert

To expand on the above answercopied by Shakti, I have actually been able to measure a performance difference between the two functions.

I was testing performance of variations of the solution to this question and found that the standard deviation and maximum runtimes were larger when using CAST.

Runtimes in milliseconds *Times in milliseconds, rounded to nearest 1/300th of a second as per the precision of the DateTime type

How to set the image from drawable dynamically in android?

imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);

Best way to concatenate List of String objects?

In java 8 you can also use a reducer, something like:

public static String join(List<String> strings, String joinStr) {
    return strings.stream().reduce("", (prev, cur) -> prev += (cur + joinStr));
}

What rules does software version numbering follow?

The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:

  • Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
  • Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
  • Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.

Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.

There are many variants to versioning. It all boils down to personal preference.

For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

I have got this error in the following 2 ways:

I was getting this error when I was pushing into another UIViewController.

HOWEVER by mistake I subclassed the other class from UITabBarController and was getting this error.

How I got it fixed? I subclassed from UIViewController and I was no longer crashing :)


I didn't want to use storyboard. So I deleted it. Yet I forget to delete its reference in the Project settings. I just clicked on the project >> General >> Deployment Info >> and I then I set the Main Interface to black space. (It was previously set to main)

As you can see for the both situations you're getting an error for accessing some object that does exist...

The shortest possible output from git log containing author and date

git log --pretty=format:"%H %an %ad"

use --date= to set a date format

git log --pretty=format:"%H %an %ad" --date=short

How to convert int to NSString?

If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:

NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];

In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.

How do I find the CPU and RAM usage using PowerShell?

I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:

$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
    $date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
    $availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
    $date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
    Start-Sleep -s 2
}

This produces the following output:

2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)

You can hit Ctrl+C to abort the loop.

So, you can connect to any Windows machine with this command:

Enter-PSSession -ComputerName MyServerName -Credential MyUserName

...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

sql server Get the FULL month name from a date

select datename(DAY,GETDATE()) +'-'+ datename(MONTH,GETDATE()) +'- '+ 
       datename(YEAR,GETDATE()) as 'yourcolumnname'

How to find the day, month and year with moment.js

If you are looking for answer in string values , try this

var check = moment('date/utc format');
day = check.format('dddd') // => ('Monday' , 'Tuesday' ----)
month = check.format('MMMM') // => ('January','February.....)
year = check.format('YYYY') // => ('2012','2013' ...)  

H.264 file size for 1 hr of HD video

I'm a friend of keeping the original files, so that you can still use the archived original ones and do new encodes from these fresh ones when the old transcodes are out of date. eg. migrating them from previously transocded mpeg2-hd to mpeg4-hd (and perhaps from mpeg4-hd to its successor in sometime). but all of these should be done from the original. any compression step will followed by a loss of quality. it will need some time to redo this again, but in my opinion it's worth the effort.

so, if you want to keep the originals, you can use the running time in seconds of you tapes times the maximum datarate of hdv (constants 27mbit/s I think) to get your needed storage capacity

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

HTML Button Close Window

JavaScript can only close a window that was opened using JavaScript. Example below:

<script>
function myFunction() {
  var str = "Sample";
  var result = str.link("https://sample.com");
  document.getElementById("demo").innerHTML = result;
}
</script>

How to import classes defined in __init__.py

Add something like this to lib/__init__.py

from .helperclass import Helper

now you can import it directly:

from lib import Helper

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

Using Google Translate in C#

If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/

A Java collection of value pairs? (tuples?)

The preferred solution as you've described it is a List of Pairs (i.e. List).

To accomplish this you would create a Pair class for use in your collection. This is a useful utility class to add to your code base.

The closest class in the Sun JDK providing functionality similar to a typical Pair class is AbstractMap.SimpleEntry. You could use this class rather than creating your own Pair class, though you would have to live with some awkward restrictions and I think most people would frown on this as not really the intended role of SimpleEntry. For example SimpleEntry has no "setKey()" method and no default constructor, so you may find it too limiting.

Bear in mind that Collections are designed to contain elements of a single type. Related utility interfaces such as Map are not actually Collections (i.e. Map does not implement the Collection interface). A Pair would not implement the Collection interface either but is obviously a useful class in building larger data structures.

Apache shows PHP code instead of executing it

open the file

/etc/apache2/httpd.conf

and change

#LoadModule php5_module libexec/apache2/libphp5.so

into

LoadModule php5_module libexec/apache2/libphp5.so

So just uncoment the PHP module load in httpd.conf

Android check permission for LocationManager

The last part of the error message you quoted states: ...with ("checkPermission") or explicitly handle a potential "SecurityException"

A much quicker/simpler way of checking if you have permissions is to surround your code with try { ... } catch (SecurityException e) { [insert error handling code here] }. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.

Is Unit Testing worth the effort?

Unit testing helps a lot in projects that are larger than any one developer can hold in their head. They allow you to run the unit test suite before checkin and discover if you broke something. This cuts down a lot on instances of having to sit and twiddle your thumbs while waiting for someone else to fix a bug they checked in, or going to the hassle of reverting their change so you can get some work done. It's also immensely valuable in refactoring, so you can be sure that the refactored code passes all the tests that the original code did.

How to check if the request is an AJAX request with PHP

Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];

<?php
function create_nonce($optional_salt='')
{
    return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>

<form>
  <input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
  <label class="form-group">
    Login<br />
    <input name="userName" id="userName" type="text" />
  </label>
  <label class="form-group">
    Password<br />
    <input name="userPassword" id="userPassword" type="password" />
  </label>
  <button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
    $("form.login button").on("click", function() {
        authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
    });

    function authorize (authUser, authPassword, authNonce) {
        $.ajax({
          type: "POST",
          url: "/inc/rpc.php",
          dataType: "json",
          data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
        })
        .success(function( msg ) {
            //some successful stuff
        });
    }
</script>

Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:

<?php
function check_nonce($nonce, $optional_salt='')
{
    $lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
    if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce || 
        hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
    {
        return true;
    } else {
        return false;
    }
}

$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
    $ret['nonce_check'] = 'passed';
} else {
    $ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>

edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

How do I split a string by a multi-character delimiter in C#?

...In short:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);

ASP.Net MVC: Calling a method from a view

You should not call a controller from the view.

Add a property to your view model, set it in the controller, and use it in the view.

Here is an example:

MyViewModel.cs:

public class MyViewModel
{   ...
    public bool ShowAdmin { get; set; }
}

MyController.cs:

public ViewResult GetAdminMenu()
    {
        MyViewModelmodel = new MyViewModel();            

        model.ShowAdmin = userHasPermission("Admin"); 

        return View(model);
    }

MyView.cshtml:

@model MyProj.ViewModels.MyViewModel


@if (@Model.ShowAdmin)
{
   <!-- admin links here-->
}

..\Views\Shared\ _Layout.cshtml:

    @using MyProj.ViewModels.Common;
....
    <div>    
        @Html.Action("GetAdminMenu", "Layout")
    </div>

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

In SQL 2012 you can use:

EXEC sp_describe_first_result_set N'SELECT * FROM [TableName]'

This will give you the column names along with their properties.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

rails bundle clean

When searching for an answer to the very same question I came across gem_unused.
You also might wanna read this article: http://chill.manilla.com/2012/12/31/clean-up-your-dirty-gemsets/
The source code is available on GitHub: https://github.com/apolzon/gem_unused

Command to collapse all sections of code?

None of these worked for me. What I found was, in the editor, search the Keyboard Shortcuts file for editor.foldRecursively. That will give you the latest binding. In my case it was CMD + K, CMD + [.

Seeking useful Eclipse Java code templates

Code Section

//--------------------------------------------------------------
//                       ${title}
//--------------------------------------------------------------
${cursor}

Use this template to make commenting sections of code easier. it's not very complex, but has saved me lots of time :)

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

The code you have for the two columns looks ok. Look for any other datetime columns on that mapping class. Also, enable logging on the datacontext to see the query and parameters.

dc.Log = Console.Out;

DateTime is initialized to c#'s 0 - which is 0001-01-01. This is transmitted by linqtosql to the database via sql string literal : '0001-01-01'. Sql cannot parse a T-Sql datetime from this date.

There's a couple ways to deal with this:

  • Make sure you initialize all date times with a value that SQL can handle (such as Sql's 0 : 1900-01-01 )
  • Make sure any date times that may occasionally be omitted are nullable datetimes

Multiple bluetooth connection

Yes, your device can simultaneously connect to 7 other Bluetooth devices at the same time, in theory. Such a connection is called a piconet. A more complex connection pattern is the scatternet.

The reason it is limited to 7 other devices is because the assigned bit field for LT_ADDR in L2CAP protocol is only 3.

Clicking the back button twice to exit an activity

Here is another way... using the CountDownTimer method

private boolean exit = false;
@Override
public void onBackPressed() {
        if (exit) {
            finish();
        } else {
            Toast.makeText(this, "Press back again to exit",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new CountDownTimer(3000,1000) {

                @Override
                public void onTick(long l) {

                }

                @Override
                public void onFinish() {
                    exit = false;
                }
            }.start();
        }

    }

How to generate a random number in C++?

If you are using boost libs you can obtain a random generator in this way:

#include <iostream>
#include <string>

// Used in randomization
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>

using namespace std;
using namespace boost;

int current_time_nanoseconds(){
    struct timespec tm;
    clock_gettime(CLOCK_REALTIME, &tm);
    return tm.tv_nsec;
}

int main (int argc, char* argv[]) {
    unsigned int dice_rolls = 12;
    random::mt19937 rng(current_time_nanoseconds());
    random::uniform_int_distribution<> six(1,6);

    for(unsigned int i=0; i<dice_rolls; i++){
        cout << six(rng) << endl;
    }
}

Where the function current_time_nanoseconds() gives the current time in nanoseconds which is used as a seed.


Here is a more general class to get random integers and dates in a range:

#include <iostream>
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"


using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::gregorian;


class Randomizer {
private:
    static const bool debug_mode = false;
    random::mt19937 rng_;

    // The private constructor so that the user can not directly instantiate
    Randomizer() {
        if(debug_mode==true){
            this->rng_ = random::mt19937();
        }else{
            this->rng_ = random::mt19937(current_time_nanoseconds());
        }
    };

    int current_time_nanoseconds(){
        struct timespec tm;
        clock_gettime(CLOCK_REALTIME, &tm);
        return tm.tv_nsec;
    }

    // C++ 03
    // ========
    // Dont forget to declare these two. You want to make sure they
    // are unacceptable otherwise you may accidentally get copies of
    // your singleton appearing.
    Randomizer(Randomizer const&);     // Don't Implement
    void operator=(Randomizer const&); // Don't implement

public:
    static Randomizer& get_instance(){
        // The only instance of the class is created at the first call get_instance ()
        // and will be destroyed only when the program exits
        static Randomizer instance;
        return instance;
    }
    bool method() { return true; };

    int rand(unsigned int floor, unsigned int ceil){
        random::uniform_int_distribution<> rand_ = random::uniform_int_distribution<> (floor,ceil);
        return (rand_(rng_));
    }

    // Is not considering the millisecons
    time_duration rand_time_duration(){
        boost::posix_time::time_duration floor(0, 0, 0, 0);
        boost::posix_time::time_duration ceil(23, 59, 59, 0);
        unsigned int rand_seconds = rand(floor.total_seconds(), ceil.total_seconds());
        return seconds(rand_seconds);
    }


    date rand_date_from_epoch_to_now(){
        date now = second_clock::local_time().date();
        return rand_date_from_epoch_to_ceil(now);
    }

    date rand_date_from_epoch_to_ceil(date ceil_date){
        date epoch = ptime(date(1970,1,1)).date();
        return rand_date_in_interval(epoch, ceil_date);
    }

    date rand_date_in_interval(date floor_date, date ceil_date){
        return rand_ptime_in_interval(ptime(floor_date), ptime(ceil_date)).date();
    }

    ptime rand_ptime_from_epoch_to_now(){
        ptime now = second_clock::local_time();
        return rand_ptime_from_epoch_to_ceil(now);
    }

    ptime rand_ptime_from_epoch_to_ceil(ptime ceil_date){
        ptime epoch = ptime(date(1970,1,1));
        return rand_ptime_in_interval(epoch, ceil_date);
    }

    ptime rand_ptime_in_interval(ptime floor_date, ptime ceil_date){
        time_duration const diff = ceil_date - floor_date;
        long long gap_seconds = diff.total_seconds();
        long long step_seconds = Randomizer::get_instance().rand(0, gap_seconds);
        return floor_date + seconds(step_seconds);
    }
};

ValueError: max() arg is an empty sequence

Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

Lastly dict.get is a method not a list or dictionary so you can't use [] with it:

Correct way is:

if frequencies.get(name):

And Pythonic way is:

if name in frequencies:

The Pythonic way to get the frequency of items is to use collections.Counter:

from collections import Counter   #Add this at the top of file.

def clkFindMost(self, parent):

        #self.listMyData = []   
        if self.listMyData:
           frequencies = Counter(self.listMyData)
           self.txtResults.Value = max(frequencies, key=frequencies.get)
        else:
           self.txtResults.Value = '' 

max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

>>> lst = []
>>> max(lst)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
    mx = max(lst)
else:
    #Handle this here

If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can't use if on them directly:

>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
       mx = max(lst)
    else:
      #Handle this here   

Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

Two way sync with rsync

You can use cloudsync to keep a folder in-sync with a remote:

pip install cloudsync
pip install cloudsync-gdrive
cloudsync sync file:c:/users/me/documents gdrive:/mydocs

If the remote is NFS, you can use:

cloudsync sync file:c:/users/me/documents/ file:/mnt/nfs/whatevs

Console output in a Qt GUI app?

First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...

Second, qDebug is fancy :)

Third, you can try adding console to your .pro's CONFIG, it might work.

What is the purpose of Order By 1 in SQL select statement?

Also see:

http://www.techonthenet.com/sql/order_by.php

For a description of order by. I learned something! :)

I've also used this in the past when I wanted to add an indeterminate number of filters to a sql statement. Sloppy I know, but it worked. :P

Changing color of Twitter bootstrap Nav-Pills

Bootstrap 4.x Solution

.nav-pills .nav-link.active {
    background-color: #ff0000 !important;
}