Programs & Examples On #Dicom

Digital Imaging and Communications in Medicine (DICOM) standard defines formats for storing and communicating medical images. Non-programming specific questions about DICOM are off-topic for Stack Overflow. For questions related to a specific tool-kit, use a more specific tag in addition to, or instead of, this tag.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

How to position one element relative to another with jQuery?

Something like this?

$(menu).css("top", targetE1.y + "px"); 
$(menu).css("left", targetE1.x - widthOfMenu + "px");

How to add image for button in android?

   <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="News Feed"
        android:icon="@drawable/newsfeed" />

newsfeed is image in the drawable folder

Remove all whitespaces from NSString

pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Set Background cell color in PHPExcel

function cellColor($cells,$color){
    global $objPHPExcel;

    $objPHPExcel->getActiveSheet()->getStyle($cells)->getFill()->applyFromArray(array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array(
             'rgb' => $color
        )
    ));
}

cellColor('B5', 'F28A8C');
cellColor('G5', 'F28A8C');
cellColor('A7:I7', 'F28A8C');
cellColor('A17:I17', 'F28A8C');
cellColor('A30:Z30', 'F28A8C');

enter image description here

How to deal with a slow SecureRandom generator?

I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a seed, then dies. The method which you call for randoms will join to that thread if it is alive so the first call only blocks if it occurs very early in program execution.

How do I use Ruby for shell scripting?

This might also be helpful: http://rush.heroku.com/

I haven't used it much, but looks pretty cool

From the site:

rush is a replacement for the unix shell (bash, zsh, etc) which uses pure Ruby syntax. Grep through files, find and kill processes, copy files - everything you do in the shell, now in Ruby

How to disable HTML button using JavaScript?

to disable

document.getElementById("btnPlaceOrder").disabled = true; 

to enable

document.getElementById("btnPlaceOrder").disabled = false; 

Process.start: how to get the output?

The solution that worked for me in win and linux is the folling

// GET api/values
        [HttpGet("cifrado/{xml}")]
        public ActionResult<IEnumerable<string>> Cifrado(String xml)
        {
            String nombreXML = DateTime.Now.ToString("ddMMyyyyhhmmss").ToString();
            String archivo = "/app/files/"+nombreXML + ".XML";
            String comando = " --armor --recipient [email protected]  --encrypt " + archivo;
            try{
                System.IO.File.WriteAllText(archivo, xml);                
                //String comando = "C:\\GnuPG\\bin\\gpg.exe --recipient [email protected] --armor --encrypt C:\\Users\\Administrador\\Documents\\pruebas\\nuevo.xml ";
                ProcessStartInfo startInfo = new ProcessStartInfo() {FileName = "/usr/bin/gpg",  Arguments = comando }; 
                Process proc = new Process() { StartInfo = startInfo, };
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.Start();
                proc.WaitForExit();
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                return new string[] { "Archivo encriptado", archivo + " - "+ comando};
            }catch (Exception exception){
                return new string[] { archivo, "exception: "+exception.ToString() + " - "+ comando };
            }
        }

Form/JavaScript not working on IE 11 with error DOM7011

I run into this when click on a html , it is fixed by adding type = "button" attribute.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I wrote this because I arrive here searching for the same error, and this could be useful for someone in the future.

I get the same error while trying to initialize a service variable from its constructor making a call to a remote API trough http.get and .subscribe()

After many tests without understanding what the problem was, i finally get it: My application had authentication and an HttpInterceptor, and i was trying to initialize the service calling a public API method using http.get(...) without 'No-Auth' headers. I added them like here, and problem solved for me:

getData() {
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });    
return this.http.get(environment.urlApi.Literales, { headers: reqHeader });  
}

What a headache :(

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT a.* FROM orders a INNER JOIN (SELECT course,MAX(id) as id FROM orders WHERE admission_id=".$id." GROUP BY course ) AS b ON a.course = b.course AND a.id = b.id

With the Above Query you will get unique records with where condition

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

How to capture the android device screen content?

AFAIK, All of the methods currently to capture a screenshot of android use the /dev/graphics/fb0 framebuffer. This includes ddms. It does require root to read from this stream. ddms uses adbd to request the information, so root is not required as adb has the permissions needed to request the data from /dev/graphics/fb0.

The framebuffer contains 2+ "frames" of RGB565 images. If you are able to read the data, you would have to know the screen resolution to know how many bytes are needed to get the image. each pixel is 2 bytes, so if the screen res was 480x800, you would have to read 768,000 bytes for the image, since a 480x800 RGB565 image has 384,000 pixels.

BigDecimal to string

To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.

new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()

will print the "10.0001"

Find files in a folder using Java

You can use a FilenameFilter, like so:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

How to paste into a terminal?

Mostly likely middle click your mouse.

Or try Shift + Insert.

It all depends on terminal used and X11-config for mouse.

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

How to create a fixed-size array of objects

One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.

var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

Difference between matches() and find() in Java Regex

matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

How can I scale an image in a CSS sprite

Here's what I did to do this. Keep in mind it won't work on IE8 and below.

#element {
  width:100%;
  height:50px;
  background:url(/path/to/image.png);
  background-position:140.112201963534% 973.333333333333%;
}

The background image's width will scale down as the parent of #element scales down. You can do the same with its height, too, if you convert height to a percentage. The only tricky bit are figuring out the percentages for background-position.

The first percentage is the width of the targeted area of the sprite when at normal width divided by the sprite's total width, and multiplied by 100.

The second percentage is the height of the targeted area of the sprite before being scaled divided by the sprite's total height, and multiplied by 100.

The wording on those two equations is a little sloppy, so let me know if you need me to explain it better.

C++ floating point to integer type conversions

I believe you can do this using a cast:

float f_val = 3.6f;
int i_val = (int) f_val;

Insert a row to pandas dataframe

It just came up to me that maybe T attribute is a valid choice. Transpose, can get away from the somewhat misleading df.loc[-1] = [2, 3, 4] as @flow2k mentioned, and it is suitable for more universal situation such as you want to insert [2, 3, 4] before arbitrary row, which is hard for concat(),append() to achieve. And there's no need to bare the trouble defining and debugging a function.

a = df.T
a.insert(0,'anyName',value=[2,3,4])
# just give insert() any column name you want, we'll rename it.
a.rename(columns=dict(zip(a.columns,[i for i in range(a.shape[1])])),inplace=True)
# set inplace to a Boolean as you need.
df=a.T
df

    A   B   C
0   2   3   4
1   5   6   7
2   7   8   9

I guess this can partly explain @MattCochrane 's complaint about why pandas doesn't have a method to insert a row like insert() does.

How to get root view controller?

Swift 3: Chage ViewController withOut Segue and send AnyObject Use: Identity MainPageViewController on target ViewController

let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController

var mainPageNav = UINavigationController(rootViewController: mainPage)

self.present(mainPageNav, animated: true, completion: nil)

or if you want to Change View Controller and send Data

let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController

let dataToSend = "**Any String**" or  var ObjectToSend:**AnyObject** 

mainPage.getData = dataToSend 

var mainPageNav = UINavigationController(rootViewController: mainPage)

self.present(mainPageNav, animated: true, completion: nil)  

jQuery Event Keypress: Which key was pressed?

Add hidden submit, not type hidden, just plain submit with style="display:none". Here is an example (removed unnecessary attributes from code).

<form>
  <input type="text">
  <input type="submit" style="display:none">
</form>

it will accept enter key natively, no need for JavaScript, works in every browser.

How to get the Touch position in android?

Supplemental answer

Given an OnTouchListener

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

set on some view:

myView.setOnTouchListener(handleTouch);

This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0). If you move your finger above the view, then y will be negative. If you move your finger left of the view, then x will be negative.

int x = (int)event.getX();
int y = (int)event.getY();

If you want the coordinates relative to the top left corner of the device screen, then use the raw values.

int x = (int)event.getRawX();
int y = (int)event.getRawY();

Related

How to add buttons dynamically to my form?

It doesn't work because the list is empty. Try this:

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < 10; i++)
    {
        Button newButton = new Button();
        buttons.Add(newButton);
        this.Controls.Add(newButton);   
    }
}

Why can't I make a vector of references?

It's a flaw in the C++ language. You can't take the address of a reference, since attempting to do so would result in the address of the object being referred to, and thus you can never get a pointer to a reference. std::vector works with pointers to its elements, so the values being stored need to be able to be pointed to. You'll have to use pointers instead.

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

Display MessageBox in ASP

If you want to do it from code behind, try this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);

Change URL parameters

I think you want the query plugin.

E.g.:

window.location.search = jQuery.query.set("rows", 10);

This will work regardless of the current state of rows.

Android: How to get a custom View's height and width?

Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Using pg_dump to only get insert statements from one table within database

Put into a script I like something like that:

#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database

BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"

# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
       mkdir $BASE_DIR
       chown -R postgres:postgres $BASE_DIR
fi

sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME

Relation between CommonJS, AMD and RequireJS?

RequireJS implements the AMD API (source).

CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this:

// someModule.js
exports.doSomething = function() { return "foo"; };

//otherModule.js
var someModule = require('someModule'); // in the vein of node    
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };

Basically, CommonJS specifies that you need to have a require() function to fetch dependencies, an exports variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies (source). CommonJS has various implementations, including Node.js, which you mentioned.

CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well (I really have no source for this--it just says so everywhere, including the RequireJS site.) Apparently, this has something to do with asynchronous loading, etc.

On the other hand, RequireJS implements AMD, which is designed to suit the browser environment (source). Apparently, AMD started as a spinoff of the CommonJS Transport format and evolved into its own module definition API. Hence the similarities between the two. The new feature in AMD is the define() function that allows the module to declare its dependencies before being loaded. For example, the definition could be:

define('module/id/string', ['module', 'dependency', 'array'], 
function(module, factory function) {
  return ModuleContents;  
});

So, CommonJS and AMD are JavaScript module definition APIs that have different implementations, but both come from the same origins.

  • AMD is more suited for the browser, because it supports asynchronous loading of module dependencies.
  • RequireJS is an implementation of AMD, while at the same time trying to keep the spirit of CommonJS (mainly in the module identifiers).

To confuse you even more, RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported for use with RequireJS.

define(function(require, exports, module) {
  var someModule = require('someModule'); // in the vein of node    
  exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});

I hope this helps to clarify things!

Test if string is a number in Ruby on Rails

use the following function:

def is_numeric? val
    return val.try(:to_f).try(:to_s) == val
end

so,

is_numeric? "1.2f" = false

is_numeric? "1.2" = true

is_numeric? "12f" = false

is_numeric? "12" = true

How can I replace a newline (\n) using sed?

This might work for you (GNU sed):

sed 'H;$!d;x;:a;s/^((.).*)\2/\1 /;ta;s/.//' file

The H command prepends a newline to the pattern space and then appends the result to the hold space. The normal flow of sed is to remove the following newline from each line, thus this will introduce a newline to the start of the hold space and the replicate the remainder of the file. Once the file has been slurped into the hold space, swap the hold space with the patten space and then use pattern matching to replace all original newlines with spaces. Finally, remove the introduced newline.

This has the advantage of never actually entering a newline string within the sed commands.

How do I execute a stored procedure once for each row returned by query?

Can this not be done with a user-defined function to replicate whatever your stored procedure is doing?

SELECT udfMyFunction(user_id), someOtherField, etc FROM MyTable WHERE WhateverCondition

where udfMyFunction is a function you make that takes in the user ID and does whatever you need to do with it.

See http://www.sqlteam.com/article/user-defined-functions for a bit more background

I agree that cursors really ought to be avoided where possible. And it usually is possible!

(of course, my answer presupposes that you're only interested in getting the output from the SP and that you're not changing the actual data. I find "alters user data in a certain way" a little ambiguous from the original question, so thought I'd offer this as a possible solution. Utterly depends on what you're doing!)

What is the largest Safe UDP Packet Size on the Internet

The theoretical limit (on Windows) for the maximum size of a UDP packet is 65507 bytes. This is documented here:

The correct maximum UDP message size is 65507, as determined by the following formula: 0xffff - (sizeof(IP Header) + sizeof(UDP Header)) = 65535-(20+8) = 65507

That being said, most protocols limit to a much smaller size - usually either 512 or occasionally 8192. You can often go higher than 548 safely if you are on a reliable network - but if you're broadcasting across the internet at large, the larger you go, the more likely you'll be to run into packet transmission problems and loss.

Finding index of character in Swift String

This worked for me,

var loc = "abcdefghi".rangeOfString("c").location
NSLog("%d", loc);

this worked too,

var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);

Most efficient way to create a zero filled JavaScript array?

Note added August 2013, updated February 2015: The answer below from 2009 relates to JavaScript's generic Array type. It doesn't relate to the newer typed arrays defined in ES2015 [and available now in many browsers], like Int32Array and such. Also note that ES2015 adds a fill method to both Arrays and typed arrays, which is likely to be the most efficient way to fill them...

Also, it can make a big difference to some implementations how you create the array. Chrome's V8 engine, in particular, tries to use a highly-efficient, contiguous-memory array if it thinks it can, shifting to the object-based array only when necessary.


With most languages, it would be pre-allocate, then zero-fill, like this:

function newFilledArray(len, val) {
    var rv = new Array(len);
    while (--len >= 0) {
        rv[len] = val;
    }
    return rv;
}

But, JavaScript arrays aren't really arrays, they're key/value maps just like all other JavaScript objects, so there's no "pre-allocate" to do (setting the length doesn't allocate that many slots to fill), nor is there any reason to believe that the benefit of counting down to zero (which is just to make the comparison in the loop fast) isn't outweighed by adding the keys in reverse order when the implementation may well have optimized their handling of the keys related to arrays on the theory you'll generally do them in order.

In fact, Matthew Crumley pointed out that counting down is markedly slower on Firefox than counting up, a result I can confirm — it's the array part of it (looping down to zero is still faster than looping up to a limit in a var). Apparently adding the elements to the array in reverse order is a slow op on Firefox. In fact, the results vary quite a bit by JavaScript implementation (which isn't all that surprising). Here's a quick and dirty test page (below) for browser implementations (very dirty, doesn't yield during tests, so provides minimal feedback and will run afoul of script time limits). I recommend refreshing between tests; FF (at least) slows down on repeated tests if you don't.

The fairly complicated version that uses Array#concat is faster than a straight init on FF as of somewhere between 1,000 and 2,000 element arrays. On Chrome's V8 engine, though, straight init wins out every time...

Here's the test page (live copy):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zero Init Test Page</title>
<style type='text/css'>
body {
    font-family:    sans-serif;
}
#log p {
    margin:     0;
    padding:    0;
}
.error {
    color:      red;
}
.winner {
    color:      green;
    font-weight:    bold;
}
</style>
<script type='text/javascript' src='prototype-1.6.0.3.js'></script>
<script type='text/javascript'>
var testdefs = {
    'downpre':  {
        total:  0,
        desc:   "Count down, pre-decrement",
        func:   makeWithCountDownPre
    },
    'downpost': {
        total:  0,
        desc:   "Count down, post-decrement",
        func:   makeWithCountDownPost
    },
    'up':       {
        total:  0,
        desc:   "Count up (normal)",
        func:   makeWithCountUp
    },
    'downandup':  {
        total:  0,
        desc:   "Count down (for loop) and up (for filling)",
        func:   makeWithCountDownArrayUp
    },
    'concat':   {
        total:  0,
        desc:   "Concat",
        func:   makeWithConcat
    }
};

document.observe('dom:loaded', function() {
    var markup, defname;

    markup = "";
    for (defname in testdefs) {
        markup +=
            "<div><input type='checkbox' id='chk_" + defname + "' checked>" +
            "<label for='chk_" + defname + "'>" + testdefs[defname].desc + "</label></div>";
    }
    $('checkboxes').update(markup);
    $('btnTest').observe('click', btnTestClick);
});

function epoch() {
    return (new Date()).getTime();
}

function btnTestClick() {

    // Clear log
    $('log').update('Testing...');

    // Show running
    $('btnTest').disabled = true;

    // Run after a pause while the browser updates display
    btnTestClickPart2.defer();
}
function btnTestClickPart2() {

    try {
        runTests();
    }
    catch (e) {
        log("Exception: " + e);
    }

    // Re-enable the button; we don't yheidl
    $('btnTest').disabled = false;
}

function runTests() {
    var start, time, counter, length, defname, def, results, a, invalid, lowest, s;

    // Get loops and length
    s = $F('txtLoops');
    runcount = parseInt(s);
    if (isNaN(runcount) || runcount <= 0) {
        log("Invalid loops value '" + s + "'");
        return;
    }
    s = $F('txtLength');
    length = parseInt(s);
    if (isNaN(length) || length <= 0) {
        log("Invalid length value '" + s + "'");
        return;
    }

    // Clear log
    $('log').update('');

    // Do it
    for (counter = 0; counter <= runcount; ++counter) {

        for (defname in testdefs) {
            def = testdefs[defname];
            if ($('chk_' + defname).checked) {
                start = epoch();
                a = def.func(length);
                time = epoch() - start;
                if (counter == 0) {
                    // Don't count (warm up), but do check the algorithm works
                    invalid = validateResult(a, length);
                    if (invalid) {
                        log("<span class='error'>FAILURE</span> with def " + defname + ": " + invalid);
                        return;
                    }
                }
                else {
                    // Count this one
                    log("#" + counter + ": " + def.desc + ": " + time + "ms");
                    def.total += time;
                }
            }
        }
    }

    for (defname in testdefs) {
        def = testdefs[defname];
        if ($('chk_' + defname).checked) {
            def.avg = def.total / runcount;
            if (typeof lowest != 'number' || lowest > def.avg) {
                lowest = def.avg;
            }
        }
    }

    results =
        "<p>Results:" +
        "<br>Length: " + length +
        "<br>Loops: " + runcount +
        "</p>";
    for (defname in testdefs) {
        def = testdefs[defname];
        if ($('chk_' + defname).checked) {
            results += "<p" + (lowest == def.avg ? " class='winner'" : "") + ">" + def.desc + ", average time: " + def.avg + "ms</p>";
        }
    }
    results += "<hr>";
    $('log').insert({top: results});
}

function validateResult(a, length) {
    var n;

    if (a.length != length) {
        return "Length is wrong";
    }
    for (n = length - 1; n >= 0; --n) {
        if (a[n] != 0) {
            return "Index " + n + " is not zero";
        }
    }
    return undefined;
}

function makeWithCountDownPre(len) {
    var a;

    a = new Array(len);
    while (--len >= 0) {
        a[len] = 0;
    }
    return a;
}

function makeWithCountDownPost(len) {
    var a;

    a = new Array(len);
    while (len-- > 0) {
        a[len] = 0;
    }
    return a;
}

function makeWithCountUp(len) {
    var a, i;

    a = new Array(len);
    for (i = 0; i < len; ++i) {
        a[i] = 0;
    }
    return a;
}

function makeWithCountDownArrayUp(len) {
    var a, i;

    a = new Array(len);
    i = 0;
    while (--len >= 0) {
        a[i++] = 0;
    }
    return a;
}

function makeWithConcat(len) {
    var a, rem, currlen;

    if (len == 0) {
        return [];
    }
    a = [0];
    currlen = 1;
    while (currlen < len) {
        rem = len - currlen;
        if (rem < currlen) {
            a = a.concat(a.slice(0, rem));
        }
        else {
            a = a.concat(a);
        }
        currlen = a.length;
    }
    return a;
}

function log(msg) {
    $('log').appendChild(new Element('p').update(msg));
}
</script>
</head>
<body><div>
<label for='txtLength'>Length:</label><input type='text' id='txtLength' value='10000'>
<br><label for='txtLoops'>Loops:</label><input type='text' id='txtLoops' value='10'>
<div id='checkboxes'></div>
<br><input type='button' id='btnTest' value='Test'>
<hr>
<div id='log'></div>
</div></body>
</html>

Create a date from day month and year with T-SQL

Sql Server 2012 has a function that will create the date based on the parts (DATEFROMPARTS). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[func_DateFromParts]'))
    DROP FUNCTION [dbo].[func_DateFromParts]
GO

CREATE FUNCTION [dbo].[func_DateFromParts]
(
    @Year INT,
    @Month INT,
    @DayOfMonth INT,
    @Hour INT = 0,  -- based on 24 hour clock (add 12 for PM :)
    @Min INT = 0,
    @Sec INT = 0
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(second, @Sec, 
            DATEADD(minute, @Min, 
            DATEADD(hour, @Hour,
            DATEADD(day, @DayOfMonth - 1, 
            DATEADD(month, @Month - 1, 
            DATEADD(Year, @Year-1900, 0))))))

END

GO

You can call it like this...

SELECT dbo.func_DateFromParts(2013, 10, 4, 15, 50, DEFAULT)

Returns...

2013-10-04 15:50:00.000

How to push object into an array using AngularJS

'Push' is for arrays.

You can do something like this:

app.js:

(function() {

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

 app.controller('myController', ['$scope', function($scope) {

    $scope.myText = "Let's go";

    $scope.arrayText = [
            'Hello',
            'world'
        ];

    $scope.addText = function() {
        $scope.arrayText.push(this.myText);
    }

 }]);

})();

index.html

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div>
      <form ng-controller="myController" ng-submit="addText()">
           <input type="text" ng-model="myText" value="Lets go">
           <input type="submit" id="submit"/>
           <pre>list={{arrayText}}</pre>
      </form>
    </div>
  </body>
</html>

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

Select data from date range between two dates

Please try:

DECLARE @FrmDt DATETIME, @ToDt DATETIME
SELECT @FrmDt='2013-01-03', @ToDt='2013-01-09'

SELECT * 
FROM Product_sales 
WHERE (@FrmDt BETWEEN From_date AND To_date) OR 
    (@ToDt BETWEEN From_date AND To_date)

Jquery Open in new Tab (_blank)

Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:

// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");

For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open options for customization.

Update:

You would need something along:

$(document).ready(function() {
  $(".product-item").click(function() {
    var productLink = $(this).find("a");

    productLink.attr("target", "_blank");
    window.open(productLink.attr("href"));

    return false;
  });
});

Note the usage of .attr():

$element.attr("attribute_name")                   // Get value of attribute.
$element.attr("attribute_name", attribute_value)  // Set value of attribute.

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Landscape printing from HTML

<style type="text/css" media="print">
.landscape { 
    width: 100%; 
    height: 100%; 
    margin: 0% 0% 0% 0%; filter: progid:DXImageTransform.Microsoft.BasicImage(Rotation=1); 
} 
</style>

If you want this style to be applied to a table then create one div tag with this style class and add the table tag within this div tag and close the div tag at the end.

This table will only print in landscape and all other pages will print in portrait mode only. But the problem is if the table size is more than the page width then we may loose some of the rows and sometimes headers also are missed. Be careful.

Have a good day.

Thank you, Naveen Mettapally.

Is there a way to remove the separator line from a UITableView?

In your viewDidLoad:

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
}

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I just had this error message running IIS Express in Visual Studio 2015. In my case I needed to be running the 64 bit version of IIS Express:

Tools ? Options ? Projects and Solutions ? Web Projects
Check the box that says "Use the 64 bit version of IIS Express for web sites and projects".

Screenshot:

Screenshot of VS options for Web Project.

How do I make a "div" button submit the form its sitting in?

To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:

$('#id-of-the-button').click(function() {document.forms[0].submit()});

Which assumes you just have the one form on the page.

Getting URL hash location, and using it in jQuery

Since jQuery 1.9, the :target selector will match the URL hash. So you could do:

$(":target").show(); // or $("ul:target").show();

Which would select the element with the ID matching the hash and show it.

Best way to get user GPS location in background in Android

Use : GCM Network Manager

Run this to start a periodic task that will be ran even after re-boot:

PeriodicTask task = new PeriodicTask.Builder()
    .setService(MyLocationService.class)
    .setTag("periodic")
    .setPeriod(30L)
    .setPersisted(true)
    .build();
mGcmNetworkManager.schedule(task);

then in onRunTask() get current location and use it (in this example, event is submitted at the end to let UI know that location was found):

    public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

The MyLocationService in whole:

public class MyLocationService extends GcmTaskService {
private static final String TAG = MyLocationService.class.getSimpleName();

private LocationManager locationManager;
private Location mCurrentLocation;

public static final String TASK_GET_LOCATION_ONCE="location_oneoff_task";
public static final String TASK_GET_LOCATION_PERIODIC="location_periodic_task";


private static final int RC_PLAY_SERVICES = 123;

@Override
public void onInitializeTasks() {
    // When your package is removed or updated, all of its network tasks are cleared by
    // the GcmNetworkManager. You can override this method to reschedule them in the case of
    // an updated package. This is not called when your application is first installed.
    //
    // This is called on your application's main thread.
    startPeriodicLocationTask(TASK_GET_LOCATION_PERIODIC,
            30L, null);
}

@Override
public int onRunTask(TaskParams taskParams) {
    Log.d(TAG, "onRunTask: " + taskParams.getTag());

    String tag = taskParams.getTag();
    Bundle extras = taskParams.getExtras();
    // Default result is success.
    int result = GcmNetworkManager.RESULT_SUCCESS;

    switch (tag) {
        case TASK_GET_LOCATION_ONCE:
            getLastKnownLocation();
            break;

        case TASK_GET_LOCATION_PERIODIC:
            getLastKnownLocation();
            break;

    }

    return result;
}


public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

public static void startOneOffLocationTask(String tag, Bundle extras) {
    Log.d(TAG, "startOneOffLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    OneoffTask.Builder taskBuilder = new OneoffTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag);

    if (extras != null) taskBuilder.setExtras(extras);

    OneoffTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}

public static void startPeriodicLocationTask(String tag, Long period, Bundle extras) {
    Log.d(TAG, "startPeriodicLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    PeriodicTask.Builder taskBuilder = new PeriodicTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag)
            .setPeriod(period)
            .setPersisted(true)
            .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED);

    if (extras != null) taskBuilder.setExtras(extras);

    PeriodicTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}




public static boolean checkPlayServicesAvailable(Activity activity) {
    GoogleApiAvailability availability = GoogleApiAvailability.getInstance();
    int resultCode = availability.isGooglePlayServicesAvailable(App.get());

    if (resultCode != ConnectionResult.SUCCESS) {
        if (availability.isUserResolvableError(resultCode)) {
            // Show dialog to resolve the error.
            availability.getErrorDialog(activity, resultCode, RC_PLAY_SERVICES).show();
        }
        return false;
    } else {
        return true;
    }
}

Also add these 2 to the AndroidManifest.xml:

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

 <application...
 <service
        android:name=".api.location.MyLocationService"
        android:exported="true"
        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
        </intent-filter>
    </service>

Python: What OS am I running on?

Watch out if you're on Windows with Cygwin where os.name is posix.

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

How do I compare two DateTime objects in PHP 5.2.8?

The following seems to confirm that there are comparison operators for the DateTime class:

dev:~# php
<?php
date_default_timezone_set('Europe/London');

$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
?>
bool(false)
bool(true)
bool(false)
dev:~# php -v
PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
dev:~#

Insert Update trigger how to determine if insert or update

CREATE TRIGGER dbo.TableName_IUD
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS 
BEGIN
    SET NOCOUNT ON;

    --
    -- Check if this is an INSERT, UPDATE or DELETE Action.
    -- 
    DECLARE @action as char(1);

    SET @action = 'I'; -- Set Action to Insert by default.
    IF EXISTS(SELECT * FROM DELETED)
    BEGIN
        SET @action = 
            CASE
                WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
                ELSE 'D' -- Set Action to Deleted.       
            END
    END
    ELSE 
        IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.

    ...

    END

Color different parts of a RichTextBox string

private void Log(string s , Color? c = null)
        {
            richTextBox.SelectionStart = richTextBox.TextLength;
            richTextBox.SelectionLength = 0;
            richTextBox.SelectionColor = c ?? Color.Black;
            richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
            richTextBox.SelectionColor = Color.Black;

        }

Task continuation on UI thread

With async you just do:

await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);

However:

await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.

In PHP, how can I add an object element to an array?

Just do:

$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;

You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

You can also do this:

$myArray[] = (object) ['name' => 'My name'];

However I would argue that's not as readable, even if it is more succinct.

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

How to check task status in Celery?

Creating an AsyncResult object from the task id is the way recommended in the FAQ to obtain the task status when the only thing you have is the task id.

However, as of Celery 3.x, there are significant caveats that could bite people if they do not pay attention to them. It really depends on the specific use-case scenario.

By default, Celery does not record a "running" state.

In order for Celery to record that a task is running, you must set task_track_started to True. Here is a simple task that tests this:

@app.task(bind=True)
def test(self):
    print self.AsyncResult(self.request.id).state

When task_track_started is False, which is the default, the state show is PENDING even though the task has started. If you set task_track_started to True, then the state will be STARTED.

The state PENDING means "I don't know."

An AsyncResult with the state PENDING does not mean anything more than that Celery does not know the status of the task. This could be because of any number of reasons.

For one thing, AsyncResult can be constructed with invalid task ids. Such "tasks" will be deemed pending by Celery:

>>> task.AsyncResult("invalid").status
'PENDING'

Ok, so nobody is going to feed obviously invalid ids to AsyncResult. Fair enough, but it also has for effect that AsyncResult will also consider a task that has successfully run but that Celery has forgotten as being PENDING. Again, in some use-case scenarios this can be a problem. Part of the issue hinges on how Celery is configured to keep the results of tasks, because it depends on the availability of the "tombstones" in the results backend. ("Tombstones" is the term use in the Celery documentation for the data chunks that record how the task ended.) Using AsyncResult won't work at all if task_ignore_result is True. A more vexing problem is that Celery expires the tombstones by default. The result_expires setting by default is set to 24 hours. So if you launch a task, and record the id in long-term storage, and more 24 hours later, you create an AsyncResult with it, the status will be PENDING.

All "real tasks" start in the PENDING state. So getting PENDING on a task could mean that the task was requested but never progressed further than this (for whatever reason). Or it could mean the task ran but Celery forgot its state.

Ouch! AsyncResult won't work for me. What else can I do?

I prefer to keep track of goals than keep track of the tasks themselves. I do keep some task information but it is really secondary to keeping track of the goals. The goals are stored in storage independent from Celery. When a request needs to perform a computation depends on some goal having been achieved, it checks whether the goal has already been achieved, if yes, then it uses this cached goal, otherwise it starts the task that will effect the goal, and sends to the client that made the HTTP request a response that indicates it should wait for a result.


The variable names and hyperlinks above are for Celery 4.x. In 3.x the corresponding variables and hyperlinks are: CELERY_TRACK_STARTED, CELERY_IGNORE_RESULT, CELERY_TASK_RESULT_EXPIRES.

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

"webxml attribute is required" error in Maven

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

This solution works for me (I was using 2.2 before). Also, I am using Java Based Configuration for Servlet 3.0 and no need to have web.xml file.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

As smnbss comments in Darin Dimitrov's answer, Prompt exists for exactly this purpose, so there is no need to create a custom attribute. From the the documentation:

Gets or sets a value that will be used to set the watermark for prompts in the UI.

To use it, just decorate your view model's property like so:

[Display(Prompt = "numbers only")]
public int Age { get; set; }

This text is then conveniently placed in ModelMetadata.Watermark. Out of the box, the default template in MVC 3 ignores the Watermark property, but making it work is really simple. All you need to do is tweaking the default string template, to tell MVC how to render it. Just edit String.cshtml, like Darin does, except that rather than getting the watermark from ModelMetadata.AdditionalValues, you get it straight from ModelMetadata.Watermark:

~/Views/Shared/EditorTemplates/String.cshtml:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })

And that is it.

As you can see, the key to make everything work is the placeholder = ViewData.ModelMetadata.Watermark bit.

If you also want to enable watermarking for multi-line textboxes (textareas), you do the same for MultilineText.cshtml:

~/Views/Shared/EditorTemplates/MultilineText.cshtml:

@Html.TextArea("", ViewData.TemplateInfo.FormattedModelValue.ToString(), 0, 0, new { @class = "text-box multi-line", placeholder = ViewData.ModelMetadata.Watermark })

How Best to Compare Two Collections in Java and Act on Them?

I'd move to lists and solve it this way:

  1. Sort both lists by id ascending using custom Comparator if objects in lists aren't Comparable
  2. Iterate over elements in both lists like in merge phase in merge sort algorithm, but instead of merging lists, you check your logic.

The code would be more or less like this:

/* Main method */
private void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {
  List<Foo> oldList = asSortedList(oldSet);
  List<Foo> newList = asSortedList(newSet);

  int oldIndex = 0;
  int newIndex = 0;
  // Iterate over both collections but not always in the same pace
  while( oldIndex < oldList.size() 
      && newIndex < newIndex.size())  {
    Foo oldObject = oldList.get(oldIndex);
    Foo newObject = newList.get(newIndex);

    // Your logic here
    if(oldObject.getId() < newObject.getId()) {
      doRemove(oldObject);
      oldIndex++;
    } else if( oldObject.getId() > newObject.getId() ) {
      doAdd(newObject);
      newIndex++;
    } else if( oldObject.getId() == newObject.getId() 
            && isModified(oldObject, newObject) ) {
      doUpdate(oldObject, newObject);
      oldIndex++;
      newIndex++;
    } else {
      ... 
    }
  }// while

  // Check if there are any objects left in *oldList* or *newList*

  for(; oldIndex < oldList.size(); oldIndex++ ) {
    doRemove( oldList.get(oldIndex) );  
  }// for( oldIndex )

  for(; newIndex < newList.size(); newIndex++ ) {
    doAdd( newList.get(newIndex) );
  }// for( newIndex ) 
}// execute( oldSet, newSet )

/** Create sorted list from collection 
    If you actually perform any actions on input collections than you should 
    always return new instance of list to keep algorithm simple.
*/
private List<Foo> asSortedList(Collection<Foo> data) {
  List<Foo> resultList;
  if(data instanceof List) {
     resultList = (List<Foo>)data;
  } else {
     resultList = new ArrayList<Foo>(data);
  }
  Collections.sort(resultList)
  return resultList;
}

Visual Studio Code Automatic Imports

I got this working by installing the various plugins below.

Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.

List of Plugins

Screenshot of Extensions

screenshot of extensions
*click for full resolution

Javascript: Setting location.href versus location

A couple of years ago, location did not work for me in IE and location.href did (and both worked in other browsers). Since then I have always just used location.href and never had trouble again. I can't remember which version of IE that was.

Tomcat 8 Maven Plugin for Java 8

An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:

<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.1.1</version>
</plugin>

Version 7.1.1 wraps a Tomcat 8.5.41

Rails how to run rake task

Sometimes Your rake tasks doesn't get loaded in console, In that case you can try the following commands

require "rake"
YourApp::Application.load_tasks
Rake::Task["Namespace:task"].invoke

Regex AND operator

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).

Connect to docker container as user other than root

Execute command as www-data user: docker exec -t --user www-data container bash -c "ls -la"

How can I conditionally require form inputs with AngularJS?

Simple you can use angular validation like :

 <input type='text'
   name='name'
   ng-model='person.name'
   ng-required='!person.lastname'/>

   <input type='text'
   name='lastname'
   ng-model='person.lastname'             
   ng-required='!person.name' /> 

You can now fill the value in only one text field. Either you can fill name or lastname. In this way you can use conditional required fill in AngularJs.

Any way to clear python's IDLE window?

As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the EditorWindow.py module and add a method and a menu item in the EditorWindow class that does something like:

self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")

and perhaps some more tag management of which I'm unaware of.

How do I encode/decode HTML entities in Ruby?

<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>

CSS - Make divs align horizontally

You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this

parent-div {
  display: flex;
  flex-wrap: wrap;
  /* for horizontal aligning of child divs */
  justify-content: center;
  /* for vertical aligning */
  align-items: center;
}

child-div {
  width: /* yoursize for each div */
  ;
}

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

How do I set up a private Git repository on GitHub? Is it even possible?

Bitbucket - Their plans seem to be the best. They give you way more than GitHub do for free accounts - in fact, I'm still only using the free plan - no need to sign up to the paid ones; plus the interface is almost identical to GitHub.

A repository on Bitbucket can have up to five private users with unlimited public or private repositories - the only thing you seem to be paying for with the paid accounts are more users to access your private repositories.

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

How to test that no exception is thrown?

If you want to test that whether your test target consumes the exception. Just leave the test as (mock collaborator using jMock2):

@Test
public void consumesAndLogsExceptions() throws Exception {

    context.checking(new Expectations() {
        {
            oneOf(collaborator).doSth();
            will(throwException(new NullPointerException()));
        }
    });

    target.doSth();
 }

The test would pass if your target does consume the exception thrown, otherwise the test would fail.

If you want to test your exception consumption logic, things get more complex. I suggest delegating the consumption to a collaborator which could be mocked. Therefore the test could be:

@Test
public void consumesAndLogsExceptions() throws Exception {
    Exception e = new NullPointerException();
    context.checking(new Expectations() {
        {
            allowing(collaborator).doSth();
            will(throwException(e));

            oneOf(consumer).consume(e);
        }
    });

    target.doSth();
 }

But sometimes it's over-designed if you just want to log it. In this case, this article(http://java.dzone.com/articles/monitoring-declarative-transac, http://blog.novoj.net/2008/09/20/testing-aspect-pointcuts-is-there-an-easy-way/) may help if you insist tdd in this case.

How do I use WPF bindings with RelativeSource?

Here's a more visual explanation in the context of a MVVM architecture:

enter image description here

new Date() is working in Chrome but not Firefox

I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:

2014-06-02 10:28:00

using this code:

new Date('2014-06-02 10:28:00').toISOString();

returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.

My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.

Using this library the following code works correctly across all browsers I tested:

moment('2014-06-02 10:28:00').format('MMM d YY')

If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.

How to make a Generic Type Cast function

While probably not as clean looking as the IConvertible approach, you could always use the straightforward checking typeof(T) to return a T:

public static T ReturnType<T>(string stringValue)
{
    if (typeof(T) == typeof(int))
        return (T)(object)1;
    else if (typeof(T) == typeof(FooBar))
        return (T)(object)new FooBar(stringValue);
    else
        return default(T);
}

public class FooBar
{
    public FooBar(string something)
    {}
}

prevent property from being serialized in web API

Works fine by just adding the: [IgnoreDataMember]

On top of the propertyp, like:

public class UserSettingsModel
{
    public string UserName { get; set; }
    [IgnoreDataMember]
    public DateTime Created { get; set; }
}

This works with ApiController. The code:

[Route("api/Context/UserSettings")]
    [HttpGet, HttpPost]
    public UserSettingsModel UserSettings()
    {
        return _contextService.GetUserSettings();
    }

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

I had the same error today. I had installed Djangostack and when I checked my task manager there were two instances of mysqld running. I checked one was for wamp server and the other was for django stack. I ended the one for django stack, restarted all services in wamp server and I was able to access phpmyadmin

Get Client Machine Name in PHP

What's this "other information"? An IP address?

In PHP, you use $_SERVER['REMOTE_ADDR'] to get the IP address of the remote client, then you can use gethostbyaddr() to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.

Add default value of datetime field in SQL Server to a timestamp

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

How do I wrap text in a pre tag?

Most succinctly, this forces content to wrap inside of a "pre" tag without breaking words. Cheers!

pre {
  white-space: pre-wrap;
  word-break: keep-all
}

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Converting string to title case

Here's the solution for that problem...

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);

How do I hide the status bar in a Swift iOS app?

 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true);
    navigationController?.navigationBar.hidden = true // for navigation bar hide
    UIApplication.sharedApplication().statusBarHidden=true; // for status bar hide
}

How to print a string multiple times?

So I take it if the user enters 2, you want the output to be something like:

!!
!!
!!
!!

Correct?

To get that, you would need something like:

rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")

for i in range(rows):
    print "!" * times_to_repeat

That would result in:

How many times to repeat per row?
>> 4
!!!!
!!!!
!!!!
!!!!

I have not tested this, but it should run error free.

Get List of connected USB Devices

Adel Hazzah's answer gives working code, Daniel Widdis's and Nedko's comments mention that you need to query Win32_USBControllerDevice and use its Dependent property, and Daniel's answer gives a lot of detail without code.

Here's a synthesis of the above discussion to provide working code that lists the directly accessible PNP device properties of all connected USB devices:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

You'll need to add exception handling if you want it. Consult Daniel's answer if you want to figure out the device tree and such.

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

How to get all child inputs of a div element (jQuery)

The 'find' method can be used to get all child inputs of a container that has already been cached to save looking it up again (whereas the 'children' method will only get the immediate children). e.g.

var panel= $("#panel");
var inputs = panel.find("input");

module.exports vs. export default in Node.js and ES6

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()

How to set xampp open localhost:8080 instead of just localhost

Open XAMPP look below the X to close the program there is a Config option click it then click service and port settings then under Apache change your main port to whatever you changed it to in the config file then click save and your good to go.

Writing a large resultset to an Excel file using POI

For now I took @Gian's advice & limited the number of records per Workbook to 500k and rolled over the rest to the next Workbook. Seems to be working decent. For the above configuration, it took me about 10 mins per workbook.

Locate Git installation folder on Mac OS X

On Mojave

The binary is in

/usr/bin/git

The related scripts are here

/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Trim string in JavaScript?

I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.

TRIM FUNCTION

function trim(str)
{
    var startpatt = /^\s/;
    var endpatt = /\s$/;

    while(str.search(startpatt) == 0)
        str = str.substring(1, str.length);

    while(str.search(endpatt) == str.length-1)
        str = str.substring(0, str.length-1);   

    return str;
}

Explanation: The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

The function can be called in the following manner as an example.

form.elements[i].value = trim(form.elements[i].value);

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

how to call an ASP.NET c# method using javascript

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

How to run a Maven project from Eclipse?

Well, you need to incorporate exec-maven-plugin, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain. You can pass argument and define which phase (test, package, integration, verify, or deploy), you want this plug-in to call your main class.

You need to add this plug-in under <build> tag and specify parameters. For example

   <project>
    ...
    ...
    <build>
     <plugins>
      <plugin>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>exec-maven-plugin</artifactId>
       <version>1.1.1</version>
       <executions>
        <execution>
         <phase>test</phase>
         <goals>
          <goal>java</goal>
         </goals>
         <configuration>
          <mainClass>my.company.name.packageName.TestMain</mainClass>
          <arguments>
           <argument>myArg1</argument>
           <argument>myArg2</argument>
          </arguments>
         </configuration>
        </execution>
       </executions>
      </plugin>
     </plugins>
    </build>
    ...
    ...
   </project>

Now, if you right-click on on the project folder and do Run As > Maven Test, or Run As > Maven Package or Run As > Maven Install, the test phase will execute and so your Main class.

How do I escape double quotes in attributes in an XML String in T-SQL?

In Jelly.core to test a literal string one would use:

&lt;core:when test="${ name == 'ABC' }"&gt; 

But if I have to check for string "Toy's R Us":

&lt;core:when test="${ name == &amp;quot;Toy&apos;s R Us&amp;quot; }"&gt;

It would be like this, if the double quotes were allowed inside:

&lt;core:when test="${ name == "Toy's R Us" }"&gt; 

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

if you have more than one classes in your classifier, you might want to use pandas-ml at that part. Confusion Matrix of pandas-ml give more detailed information. check that

RESULT

What is a "thread" (really)?

Processes are like two people using two different computers, who use the network to share data when necessary. Threads are like two people using the same computer, who don't have to share data explicitly but must carefully take turns.

Conceptually, threads are just multiple worker bees buzzing around in the same address space. Each thread has its own stack, its own program counter, etc., but all threads in a process share the same memory. Imagine two programs running at the same time, but they both can access the same objects.

Contrast this with processes. Processes each have their own address space, meaning a pointer in one process cannot be used to refer to an object in another (unless you use shared memory).

I guess the key things to understand are:

  • Both processes and threads can "run at the same time".
  • Processes do not share memory (by default), but threads share all of their memory with other threads in the same process.
  • Each thread in a process has its own stack and its own instruction pointer.

How to re-render flatlist?

In react-native-flatlist, they are a property called as extraData. add the below line to your flatlist.

 <FlatList
          data={data }
          style={FlatListstyles}
          extraData={this.state}
          renderItem={this._renderItem}
       />

Date Comparison using Java

If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:


    // Convert user input into year, month, and day integers
    Date toDate = new Date(year - 1900, month - 1, day + 1);
    Date currentDate = new Date();
    boolean runThatReport = toDate.after(currentDate);

Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces... please use LTRIM/RTRIM

 LTRIM(String)
 RTRIM(String)

The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.

SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers

Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

This worked for me:

    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.7.0_05</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>

Wordpress plugin install: Could not create directory

I was on XAMPP for linux localhost and this worked for me:

sudo chown -R my-linux-username wp-content

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

CSS text-align: center; is not centering things

Use display: block; margin: auto; it will center the div

How to add multiple font files for the same font?

nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  src: url('#{$fa-font-path}/fa-solid-900.eot');
  src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
  url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400;
  src: url('#{$fa-font-path}/fa-regular-400.eot');
  src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
  url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Kill the previous instance of tomcat or the process that's running on 8080.

Go to terminal and do this:

lsof -i :8080

The output will be something like:

COMMAND   PID   USER      FD   TYPE  DEVICE SIZE/OFF NODE NAME
java    76746   YourName  57u  IPv6 0xd2a83c9c1e75      0t0    TCP *:http-alt (LISTEN)

Kill this process using it's PID:

kill 76746

How to reload a div without reloading the entire page?

write a button tag and on click function

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

What's the difference between all the Selection Segues?

The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1

Can't copy the icons here, but here are the descriptions:

  • Show: Present the content in the detail or master area depending on the content of the screen.

    If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.

  • Show Detail: Present the content in the detail area.

    If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.

  • Present Modally: Present the content modally.

  • Present as Popover: Present the content as a popover anchored to an existing view.

  • Custom: Create your own behaviors by using a custom segue.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

Get content uri from file path in android

Try with:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));

Or with:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Determine a string's encoding in C#

Another option, very late in coming, sorry:

http://www.architectshack.com/TextFileEncodingDetector.ashx

This small C#-only class uses BOMS if present, tries to auto-detect possible unicode encodings otherwise, and falls back if none of the Unicode encodings is possible or likely.

It sounds like UTF8Checker referenced above does something similar, but I think this is slightly broader in scope - instead of just UTF8, it also checks for other possible Unicode encodings (UTF-16 LE or BE) that might be missing a BOM.

Hope this helps someone!

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
fs.Close();
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
try
{
    if (bt != null)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        Response.BinaryWrite(bt);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        Response.Flush();
        // Response.End();
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    throw ex;
}
finally
{
    Response.End();
}

string decode utf-8

the core functions are getBytes(String charset) and new String(byte[] data). you can use these functions to do UTF-8 decoding.

UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String() is the byte array, which calling is equal to new String(bytes, "UTF-8")

Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.

The decoding sentence should be

String decoded = new String(encoded.getBytes("ISO-8859-1"));

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

How to iterate over the keys and values with ng-repeat in AngularJS?

    Use below code it is working to display your key and value here is key start with 1:
         <tr ng-repeat="(key,value) in alert_list" >
                   <td>{{key +1}}</td>
                   <td>{{value.title}}</td>
                 </tr>
Below is document link for it. 

https://docs.angularjs.org/api/ng/directive/ngRepeat

How do you render primitives as wireframes in OpenGL?

use this function: void glPolygonMode( GLenum face, GLenum mode);

face : Specifies the polygons that mode applies to. can be GL_FRONT for front side of the polygone and GL_BACK for his back and GL_FRONT_AND_BACK for both.

mode : Three modes are defined and can be specified in mode:

GL_POINT :Polygon vertices that are marked as the start of a boundary edge are drawn as points.

GL_LINE : Boundary edges of the polygon are drawn as line segments. (your target)

GL_FILL : The interior of the polygon is filled.

P.S : glPolygonMode controls the interpretation of polygons for rasterization in the graphics pipeline.

for more information look at the OpenGL reference pages in khronos group : https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glPolygonMode.xhtml

Get week of year in JavaScript like in PHP

Here is a slight adaptation for Typescript that will also return the dates for the week start and week end. I think it's common to have to display those in a user interface, since people don't usually remember week numbers.

_x000D_
_x000D_
function getWeekNumber(d: Date) {
  // Copy date so don't modify original
  d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  // Set to nearest Thursday: current date + 4 - current day number Make
  // Sunday's day number 7
  d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
  // Get first day of year
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  // Calculate full weeks to nearest Thursday
  const weekNo = Math.ceil(
    ((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
  );

  const weekStartDate = new Date(d.getTime());
  weekStartDate.setUTCDate(weekStartDate.getUTCDate() - 3);

  const weekEndDate = new Date(d.getTime());
  weekEndDate.setUTCDate(weekEndDate.getUTCDate() + 3);

  return [d.getUTCFullYear(), weekNo, weekStartDate, weekEndDate] as const;
}
_x000D_
_x000D_
_x000D_

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

Align image to left of text on same line - Twitter Bootstrap3

I would use Bootstrap's grid to achieve the desired result. The class="img-responsive" works nicely. Something like:

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3"><img src="./pictures/placeholder.jpg" class="img-responsive" alt="Some picture" width="410" height="307"></div>
            <div class="col-md-9"><h1>Heading</h1><p>Your Information.</p></div>
        </div>
    </div>

Convert all data frame character columns to factors

Working with dplyr

library(dplyr)

df <- data.frame(A = factor(LETTERS[1:5]),
                 B = 1:5, C = as.logical(c(1, 1, 0, 0, 1)),
                 D = letters[1:5],
                 E = paste(LETTERS[1:5], letters[1:5]),
                 stringsAsFactors = FALSE)

str(df)

we get:

'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

Now, we can convert all chr to factors:

df <- df%>%mutate_if(is.character, as.factor)
str(df)

And we get:

'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

Let's provide also other solutions:

With base package:

df[sapply(df, is.character)] <- lapply(df[sapply(df, is.character)], 
                                                           as.factor)

With dplyr 1.0.0

df <- df%>%mutate(across(where(is.factor), as.character))

With purrr package:

library(purrr)

df <- df%>% modify_if(is.factor, as.character) 

How to change Jquery UI Slider handle

If you should need to replace the handle with something else entirely, rather than just restyling it:

You can specify custom handle elements by creating and appending the elements and adding the ui-slider-handle class before initialization.

Working Example

_x000D_
_x000D_
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
  range: "min",_x000D_
  value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
  background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
  width: 14px;_x000D_
  height: 18px;_x000D_
  margin-left: -5px;_x000D_
  top: -4px;_x000D_
  border: none;_x000D_
  background: none;_x000D_
}_x000D_
.slider {_x000D_
  height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
_x000D_
_x000D_

Load and execution sequence of a web page?

Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.

How to disable Paste (Ctrl+V) with jQuery?

_x000D_
_x000D_
 $(document).ready(function(){_x000D_
   $('#txtInput').on("cut copy paste",function(e) {_x000D_
      e.preventDefault();_x000D_
   });_x000D_
});
_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <input type="text" id="txtInput" />
_x000D_
_x000D_
_x000D_

Convert list to tuple in Python

To add another alternative to tuple(l), as of Python >= 3.5 you can do:

t = *l,  # or t = (*l,) 

short, a bit faster but probably suffers from readability.

This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma ,.


P.s: The error you are receiving is due to masking of the name tuple i.e you assigned to the name tuple somewhere e.g tuple = (1, 2, 3).

Using del tuple you should be good to go.

How can I build a recursive function in python?

Recursive function example:

def recursive(string, num):
    print "#%s - %s" % (string, num)
    recursive(string, num+1)

Run it with:

recursive("Hello world", 0)

UTF-8 all the way through

In addition to setting default_charset in php.ini, you can send the correct charset using header() from within your code, before any output:

header('Content-Type: text/html; charset=utf-8');

Working with Unicode in PHP is easy as long as you realize that most of the string functions don't work with Unicode, and some might mangle strings completely. PHP considers "characters" to be 1 byte long. Sometimes this is okay (for example, explode() only looks for a byte sequence and uses it as a separator -- so it doesn't matter what actual characters you look for). But other times, when the function is actually designed to work on characters, PHP has no idea that your text has multi-byte characters that are found with Unicode.

A good library to check into is phputf8. This rewrites all of the "bad" functions so you can safely work on UTF8 strings. There are extensions like the mbstring extension that try to do this for you, too, but I prefer using the library because it's more portable (but I write mass-market products, so that's important for me). But phputf8 can use mbstring behind the scenes, anyway, to increase performance.

Select dropdown with fixed width cutting off content in IE

Not javascript free i'm afraid, but I managed to make it quite small using jQuery

$('#del_select').mouseenter(function () {

    $(this).css("width","auto");

});

$('#del_select').mouseout(function () {

    $(this).css("width","170px");

}); 

Disabling SSL Certificate Validation in Spring RestTemplate

This problem is about SSL connection. When you try to connect to some resource https protocol requires to create secured connection. That means only your browser and website server know what data is being sent in requests bodies. This security is achieved by ssl certificates that stored on website and are being downloaded by your browser (or any other client, Spring RestTemplate with Apache Http Client behind in our case) with first connection to host. There are RSA256 encryption and many other cool things around. But in the end of a day: In case certificate is not registered or is invalid you will see certificate error (HTTPS connection is not secure). To fix certificate error website provider need to buy it for particular website or fix somehow e.g. https://www.register.com/ssl-certificates

Right way how problem can be solved

  • Register SSL certificate

Not a right way how problem can be solved

  • download broken SSL certificate from website
  • import SSL certificate to Java cacerts (certificate storage)

    keytool -importcert -trustcacerts -noprompt -storepass changeit -alias citrix -keystore "C:\Program Files\Java\jdk-11.0.2\lib\security\cacerts" -file citrix.cer

Dirty (Insecure) way how problem can be solved

  • make RestTemplate to ignore SSL verification

    @Bean
    public RestTemplateBuilder restTemplateBuilder(@Autowired SSLContext sslContext) {
        return new RestTemplateBuilder() {
            @Override
            public ClientHttpRequestFactory buildRequestFactory() {
                return new HttpComponentsClientHttpRequestFactory(
                        HttpClients.custom().setSSLSocketFactory(
                                new SSLConnectionSocketFactory(sslContext
                                        , NoopHostnameVerifier.INSTANCE)).build());
            }
        };
    }
    
    @Bean
        public SSLContext insecureSslContext() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
           return SSLContexts.custom()
                    .loadTrustMaterial(null, (x509Certificates, s) -> true)
                    .build();
        }
    

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

How can I change a file's encoding with vim?

It could be useful to change the encoding just on the command line before the file is read:

rem On MicroSoft Windows
vim --cmd "set encoding=utf-8" file.ext
# In *nix shell
vim --cmd 'set encoding=utf-8' file.ext

See starting, --cmd.

What are the uses of "using" in C#?

Another example of a reasonable use in which the object is immediately disposed:

using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
{
    while (myReader.Read()) 
    {
        MyObject theObject = new MyObject();
        theObject.PublicProperty = myReader.GetString(0);
        myCollection.Add(theObject);
    }
}

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

If java 8 or above is used then the problem is the libraries we use are incompatible with java 8. So to solve this add these two lines to build.gradle of your app and all sub modules if any. (Android studio clearly show how to do this in error message)

targetCompatibility = '1.7' sourceCompatibility = '1.7'

JFrame Exit on close Java

If you don't extend JFrame and use JFrame itself in variable, you can use:

frame.dispose();
System.exit(0);

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

How can you find out which process is listening on a TCP or UDP port on Windows?

You can also check the reserved ports with the command below. Hyper-V reserve some ports, for instance.

netsh int ipv4 show excludedportrange protocol=tcp

Deleting objects from an ArrayList in Java

int sizepuede= listaoptionVO.size();
for (int i = 0; i < sizepuede; i++) {
    if(listaoptionVO.get(i).getDescripcionRuc()==null){
        listaoptionVO.remove(listaoptionVO.get(i));
        i--;
        sizepuede--;
     }
}

edit: added indentation

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

Reset CSS display property to default value

According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!

If I'm correct, I have a good solution for you which is using another class name for the element:

steps:

  1. set the default styles in style sheet as usual according to your desire.
  2. define a new class name in style sheet and add the new style you want.
  3. when you want to trigger between styles, add the new class name to the element or remove it.

if you want to edit or set a new style, get the element by the new class name and edit the style as desired.

I hope this helps. Regards!

When should one use a spinlock instead of mutex?

Continuing with Mecki's suggestion, this article pthread mutex vs pthread spinlock on Alexander Sandler's blog, Alex on Linux shows how the spinlock & mutexes can be implemented to test the behavior using #ifdef.

However, be sure to take the final call based on your observation, understanding as the example given is an isolated case, your project requirement, environment may be entirely different.

remove item from stored array in angular 2

Sometimes, splice is not enough especially if your array is involved in a FILTER logic. So, first of all you could check if your element does exist to be absolute sure to remove that exact element:

if (array.find(x => x == element)) {
   array.splice(array.findIndex(x => x == element), 1);
}

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

ResultSet exception - before start of result set

Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.

 result.next();
 String foundType = result.getString(1);

It is common to do this in an if statement or loop.

if(result.next()){
   foundType = result.getString(1);
}

static function in C

The static keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.

Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.

Detect whether current Windows version is 32 bit or 64 bit

I used this within a login script to detect 64 bit Windows

if "%ProgramW6432%" == "%ProgramFiles%" goto is64flag

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

A corresponding cross for ✓ &#x2713; would be ✗ &#x2717; I think (Dingbats).

Add UIPickerView & a Button in Action sheet - How?

Yep ! I finally Find it.

implement following code on your button click event, to pop up action sheet as given in the image of question.

UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
                                             delegate:self
                                    cancelButtonTitle:nil
                               destructiveButtonTitle:nil
                                    otherButtonTitles:nil];

UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
    theDatePicker.datePickerMode = UIDatePickerModeDate;
    theDatePicker.maximumDate=[NSDate date];
}else {
    theDatePicker.datePickerMode = UIDatePickerModeTime;
}

self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];

pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];

NSMutableArray *barItems = [[NSMutableArray alloc] init];

UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];

[pickerDateToolbar setItems:barItems animated:YES];

[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];

How to remove index.php from URLs?

How about this in your .htaccess:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

stopPropagation vs. stopImmediatePropagation

A small example to demonstrate how both these propagation stoppages work.

_x000D_
_x000D_
var state = {_x000D_
  stopPropagation: false,_x000D_
  stopImmediatePropagation: false_x000D_
};_x000D_
_x000D_
function handlePropagation(event) {_x000D_
  if (state.stopPropagation) {_x000D_
    event.stopPropagation();_x000D_
  }_x000D_
_x000D_
  if (state.stopImmediatePropagation) {_x000D_
    event.stopImmediatePropagation();_x000D_
  }_x000D_
}_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("First event handler on #child");_x000D_
});_x000D_
_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Second event handler on #child");_x000D_
});_x000D_
_x000D_
// First this event will fire on the child element, then propogate up and_x000D_
// fire for the parent element._x000D_
$("div").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Event handler on div: #" + this.id);_x000D_
});_x000D_
_x000D_
_x000D_
// Enable/disable propogation_x000D_
$("button").click(function() {_x000D_
  var objectId = this.id;_x000D_
  $(this).toggleClass('active');_x000D_
  state[objectId] = $(this).hasClass('active');_x000D_
  console.log('---------------------');_x000D_
});
_x000D_
div {_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
#parent {_x000D_
  background-color: #CCC;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  background-color: #000;_x000D_
  padding: 5em;_x000D_
}_x000D_
_x000D_
button {_x000D_
  padding: 1em;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
.active {_x000D_
  background-color: green;_x000D_
  color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="parent">_x000D_
  <div id="child">&nbsp;</div>_x000D_
</div>_x000D_
_x000D_
<button id="stopPropagation">Stop Propogation</button>_x000D_
<button id="stopImmediatePropagation" ">Stop Immediate Propogation</button>
_x000D_
_x000D_
_x000D_

There are three event handlers bound. If we don’t stop any propagation, then there should be four alerts - three on the child div, and one on the parent div.

If we stop the event from propagating, then there will be 3 alerts (all on the inner child div). Since the event won’t propagate up the DOM hierarchy, the parent div won’t see it, and its handler won’t fire.

If we stop propagation immediately, then there will only be 1 alert. Even though there are three event handlers attached to the inner child div, only 1 is executed and any further propagation is killed immediately, even within the same element.

How to block users from closing a window in Javascript?

Take a look at onBeforeUnload.

It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

Edit: Most browsers no longer allow a custom message for onbeforeunload.

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.

In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.

Firefox already does this[...]

Use string in switch case in java

We can apply Switch just on data type compatible int :short,Shor,byte,Byte,int,Integer,char,Character or enum type.

How to call a method after a delay in Android

A suitable solution in android:

private static long SLEEP_TIME = 2 // for 2 second
.
.
MyLauncher launcher = new MyLauncher();
            launcher.start();
.
.
private class MyLauncher extends Thread {
        @Override
        /**
         * Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any. 
         */
        public void run() {
            try {
                // Sleeping
                Thread.sleep(SLEEP_TIME * 1000);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            //do something you want to do
           //And your code will be executed after 2 second
        }
    }

Why are Python lambdas useful?

I can give you an example where I actually needed lambda serious. I'm making a graphical program, where the use right clicks on a file and assigns it one of three options. It turns out that in Tkinter (the GUI interfacing program I'm writing this in), when someone presses a button, it can't be assigned to a command that takes in arguments. So if I chose one of the options and wanted the result of my choice to be:

print 'hi there'

Then no big deal. But what if I need my choice to have a particular detail. For example, if I choose choice A, it calls a function that takes in some argument that is dependent on the choice A, B or C, TKinter could not support this. Lamda was the only option to get around this actually...

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

HTML: Changing colors of specific words in a string of text

You could use the longer boringer way

_x000D_
_x000D_
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 
_x000D_
_x000D_
_x000D_

you get the point for the rest

Is it possible to display inline images from html in an Android TextView?

You could also write your own parser to pull the URL of all the images and then dynamically create new imageviews and pass in the urls.

How to send an email from JavaScript

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Use Ajax to send request to the PHP script ,check that required field are not empty or incorrect using js also keep a record of mail send by whom from your server.

function sendMail() is good for doing that.

Check for any error caught while mailing from your script and take appropriate action.
For resolving it for example if the mail address is incorrect or mail is not send due to server problem or it's in queue in such condition report it to user immediately and prevent multi sending same email again and again. Get response from your script Using jQuery GET and POST

$.get(URL,callback); $.post(URL,callback);

C#: Looping through lines of multiline string

from MSDN for StringReader

    string textReaderText = "TextReader is the abstract base " +
        "class of StreamReader and StringReader, which read " +
        "characters from streams and strings, respectively.\n\n" +

        "Create an instance of TextReader to open a text file " +
        "for reading a specified range of characters, or to " +
        "create a reader based on an existing stream.\n\n" +

        "You can also use an instance of TextReader to read " +
        "text from a custom backing store using the same " +
        "APIs you would use for a string or a stream.\n\n";

    Console.WriteLine("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);

C# ListView Column Width Auto

I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.

private void ResizeListViewColumns(ListView lv)
{
    foreach(ColumnHeader column in lv.Columns)
    {
        column.Width = -2;
    }
}

The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView.

SQL Last 6 Months

Try this one

where datediff(month, datetime_column, getdate()) <= 6

To exclude or filter out future dates

where datediff(month, datetime_column, getdate()) between 0 and 6


This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:

Result
1
2
3
4
5
6
7
8
9
10

This is Our final condition to get last 6 months data

where result <= 6

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Sending a get request with axios from a webpage, I needed (finally) to enable also Geocoding API.

I also have Places API, Maps Javascript API, and Geolocation API.

Thanks to these guys

Auto-redirect to another HTML page

If you want to redirect your webpage to another HTML FILE, just use as followed:

<meta http-equiv="refresh" content"2;otherpage.html">

2 being the seconds you want the client to wait before redirecting. Use "url=" only when it's an URL, to redirect to an HTML file just write the name after the ';'

Simulating Button click in javascript

Or you can use what JQuery alreay made for you:

http://jqueryui.com/datepicker/#icon-trigger

It's what you are trying to achieve isn't it?

How to find tag with particular text with Beautiful Soup?

With bs4 4.7.1+ you can use :contains pseudo class to specify the td containing your search string

from bs4 import BeautifulSoup
html = '''
<tr>
  <td class="pos">\n
      "Some text:"\n
      <br>\n
      <strong>some value</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Fixed text:"\n
      <br>\n
      <strong>text I am looking for</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Some other text:"\n
      <br>\n
      <strong>some other value</strong>\n
  </td>
</tr>'''
soup = bs(html, 'lxml')
print(soup.select_one('td:contains("Fixed text:")'))

How to clear out session on log out

Go to file Global.asax.cs in your project and add the following code.

    protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
        Response.Cache.SetNoStore();
    }

It worked for me..! Reference link Clear session on Logout MVC 4

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Using Panel or PlaceHolder

The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

The Panel does have outer HTML tags but does have some cool extra properties.

  • BackImageUrl: Gets/Sets the background image's URL for the panel

  • HorizontalAlign: Gets/Sets the
    horizontal alignment of the parent's contents

  • Wrap: Gets/Sets whether the
    panel's content wraps

There is a good article at startvbnet here.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Since the question was asked the Angular team has solved this issue by making it possible to dynamically create input names.

With Angular version 1.3 and later you can now do this:

<form name="vm.myForm" novalidate>
  <div ng-repeat="p in vm.persons">
    <input type="text" name="person_{{$index}}" ng-model="p" required>
    <span ng-show="vm.myForm['person_' + $index].$invalid">Enter a name</span>
  </div>
</form>

Demo

Angular 1.3 also introduced ngMessages, a more powerful tool for form validation. You can use the same technique with ngMessages:

<form name="vm.myFormNgMsg" novalidate>
    <div ng-repeat="p in vm.persons">
      <input type="text" name="person_{{$index}}" ng-model="p" required>
      <span ng-messages="vm.myFormNgMsg['person_' + $index].$error">
        <span ng-message="required">Enter a name</span>
      </span>
    </div>
  </form>

How can I change or remove HTML5 form validation default error messages?

As you can see here:

html5 oninvalid doesn't work after fixed the input field

Is good to you put in that way, for when you fix the error disapear the warning message.

<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />

.keyCode vs. .which

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

Is it possible to use Java 8 for Android development?

addd this line into module lvl build gradel

compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }

Play/pause HTML 5 video using JQuery

Found the answer here @ToolmakerSteve, but had to fine tune this way: To pause all

$('video').each(function(index){
    $(this).get(0).pause();
});

or to play all

$('video').each(function(index){
    $(this).get(0).play();
});