Programs & Examples On #Mixins

A mixin is a way to enhance an object with properties or methods from another object without inheriting from that object.

Syntax for if/else condition in SCSS mixin

You could try this:

$width:auto;
@mixin clearfix($width) {

   @if $width == 'auto' {

    // if width is not passed, or empty do this

   } @else {
        display: inline-block;
        width: $width;
   }
}

I'm not sure of your intended result, but setting a default value should return false.

What is a mixin, and why are they useful?

I read that you have a c# background. So a good starting point might be a mixin implementation for .NET.

You might want to check out the codeplex project at http://remix.codeplex.com/

Watch the lang.net Symposium link to get an overview. There is still more to come on documentation on codeplex page.

regards Stefan

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

Difference between xcopy and robocopy

The most important difference is that robocopy will (usually) retry when an error occurs, while xcopy will not. In most cases, that makes robocopy far more suitable for use in a script.

Addendum: for completeness, there is one known edge case issue with robocopy; it may silently fail to copy files or directories whose names contain invalid UTF-16 sequences. If that's a problem for you, you may need to look at third-party tools, or write your own.

Check if a variable is between two numbers with Java

I see some errors in your code.
Your probably meant the mathematical term

90 <= angle <= 180, meaning angle in range 90-180.

if (angle >= 90 && angle <= 180) {

// do action
}

How do I get the name of the current executable in C#?

On .Net Core (or Mono), most of the answers won't apply when the binary defining the process is the runtime binary of Mono or .Net Core (dotnet) and not your actual application you're interested in. In that case, use this:

var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);

Draw on HTML5 Canvas using a mouse

Here is my very simple working canvas draw and erase.

https://jsfiddle.net/richardcwc/d2gxjdva/

_x000D_
_x000D_
//Canvas_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
//Variables_x000D_
var canvasx = $(canvas).offset().left;_x000D_
var canvasy = $(canvas).offset().top;_x000D_
var last_mousex = last_mousey = 0;_x000D_
var mousex = mousey = 0;_x000D_
var mousedown = false;_x000D_
var tooltype = 'draw';_x000D_
_x000D_
//Mousedown_x000D_
$(canvas).on('mousedown', function(e) {_x000D_
    last_mousex = mousex = parseInt(e.clientX-canvasx);_x000D_
 last_mousey = mousey = parseInt(e.clientY-canvasy);_x000D_
    mousedown = true;_x000D_
});_x000D_
_x000D_
//Mouseup_x000D_
$(canvas).on('mouseup', function(e) {_x000D_
    mousedown = false;_x000D_
});_x000D_
_x000D_
//Mousemove_x000D_
$(canvas).on('mousemove', function(e) {_x000D_
    mousex = parseInt(e.clientX-canvasx);_x000D_
    mousey = parseInt(e.clientY-canvasy);_x000D_
    if(mousedown) {_x000D_
        ctx.beginPath();_x000D_
        if(tooltype=='draw') {_x000D_
            ctx.globalCompositeOperation = 'source-over';_x000D_
            ctx.strokeStyle = 'black';_x000D_
            ctx.lineWidth = 3;_x000D_
        } else {_x000D_
            ctx.globalCompositeOperation = 'destination-out';_x000D_
            ctx.lineWidth = 10;_x000D_
        }_x000D_
        ctx.moveTo(last_mousex,last_mousey);_x000D_
        ctx.lineTo(mousex,mousey);_x000D_
        ctx.lineJoin = ctx.lineCap = 'round';_x000D_
        ctx.stroke();_x000D_
    }_x000D_
    last_mousex = mousex;_x000D_
    last_mousey = mousey;_x000D_
    //Output_x000D_
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);_x000D_
});_x000D_
_x000D_
//Use draw|erase_x000D_
use_tool = function(tool) {_x000D_
    tooltype = tool; //update_x000D_
}
_x000D_
canvas {_x000D_
    cursor: crosshair;_x000D_
    border: 1px solid #000000;_x000D_
}
_x000D_
<canvas id="canvas" width="800" height="500"></canvas>_x000D_
<input type="button" value="draw" onclick="use_tool('draw');" />_x000D_
<input type="button" value="erase" onclick="use_tool('erase');" />_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

Assign variable in if condition statement, good practice or not?

There is one case when you do it, with while-loops.
When reading files, you usualy do like this:

void readFile(String pathToFile) {
    // Create a FileInputStream object
    FileInputStream fileIn = null;
    try {
        // Create the FileInputStream
        fileIn = new FileInputStream(pathToFile);
        // Create a variable to store the current line's text in
        String currentLine;
        // While the file has lines left, read the next line,
        // store it in the variable and do whatever is in the loop
        while((currentLine = in.readLine()) != null) {
            // Print out the current line in the console
            // (you can do whatever you want with the line. this is just an example)
            System.out.println(currentLine);
        }
    } catch(IOException e) {
        // Handle exception
    } finally {
        try {
            // Close the FileInputStream
            fileIn.close();
        } catch(IOException e) {
            // Handle exception
        }
    }
}

Look at the while-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if-statement, but I guess a while loop can be included in your question as well.

The reason to this is that when using a FileInputStream, every time you call FileInputStream.readLine(), it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null, and then called it from inside of the loop too, you would only get every second line.

Hope you understand, and good luck!

Change border color on <select> HTML form

As Diodeus stated, IE doesn't allow anything but the default border for <select> elements. However, I know of two hacks to achieve a similar effect :

  1. Use a DIV that is placed absolutely at the same position as the dropdown and set it's borders. It will appear that the dropdown has a border.

  2. Use a Javascript solution, for instance, the one provided here.

It may however prove to be too much effort, so you should evaluate if you really require the border.

How to iterate over a TreeMap?

Assuming type TreeMap<String,Integer> :

for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();

  System.out.println(key + " => " + value);
}

(key and Value types can be any class of course)

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

How to stop a setTimeout loop?

You need to use a variable to track "doneness" and then test it on every iteration of the loop. If done == true then return.

var done = false;

function setBgPosition() {
    if ( done ) return;
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        if ( done ) return;
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}

setBgPosition(); // start the loop

setTimeout( function(){ done = true; }, 5000 ); // external event to stop loop

PHP + MySQL transactions examples

I think I have figured it out, is it right?:

mysql_query("START TRANSACTION");

$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");

if ($a1 and $a2) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

Can a CSV file have a comment?

If you need something like:

  ¦ A                              ¦ B
--+--------------------------------+---
1 ¦ #My comment, something else    ¦
2 ¦ 1                              ¦ 2

Your CSV may contain the following lines:

"#My comment, something else"
1,2

Pay close attention at the 'quotes' in the first line.

When converting your text to columns using the Excel wizard, remember checking the 'Treat consecutive delimiters as one', setting it to use 'quotes' as delimiter.

Thus, Excel will split the text at the commas, keeping the 'comment' line as a single column value (and it will remove the quotes).

File upload along with other object in Jersey restful web service

You can access the Image File and data from a form using MULTIPART FORM DATA By using the below code.

@POST
@Path("/UpdateProfile")
@Consumes(value={MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})
@Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response updateProfile(
    @FormDataParam("file") InputStream fileInputStream,
    @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
    @FormDataParam("ProfileInfo") String ProfileInfo,
    @FormDataParam("registrationId") String registrationId) {

    String filePath= "/filepath/"+contentDispositionHeader.getFileName();

    OutputStream outputStream = null;
    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(filePath));

        while ((read = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) { 
            try {
                outputStream.close();
            } catch(Exception ex) {}
        }
    }
}

How to change cursor from pointer to finger using jQuery?

$('selector').css('cursor', 'pointer'); // 'default' to revert

I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".

The normal arrow cursor is just "default".

all possible default pointer looks DEMO

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

Properly close mongoose's connection once you're done

Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:

let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
    db = dbConnection;
    afterwards();
});


function afterwards(){

    //do stuff

    db.disconnect();
}

or if inside Async function:

(async ()=>{
    const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                  true })

    //do stuff

    db.disconnect()
})

otherwise when i was checking it in my environment it has an error.

Appropriate datatype for holding percent values?

If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.

EDIT: The decimal type is probably a better match. Then you don't need to manually scale. It takes 5 bytes per value.

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

center a row using Bootstrap 3

you can use grid system without adding empty columns

<div class="col-xs-2 center-block" style="float:none"> ... </div>

change col-xs-2 to suit your layout.

check preview: http://jsfiddle.net/rashivkp/h4869dja/

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

Change the Theme in Jupyter Notebook?

Follow these steps

Install jupyterthemes with pip:

pip install jupyterthemes

Then Choose the themes from the following and set them using the following command, Once you have installed successfully, Many of us thought we need to start the jupyter server again, just refresh the page.

Set the theme with the following command:

jt -t <theme-name>

Available themes:

  • onedork
  • grade3
  • oceans16
  • chesterish
  • monokai
  • solarizedl
  • solarizedd

Screens of the available themes are also available in the Github repository.

How to decrease prod bundle size?

Firstly, vendor bundles are huge simply because Angular 2 relies on a lot of libraries. Minimum size for Angular 2 app is around 500KB (250KB in some cases, see bottom post).
Tree shaking is properly used by angular-cli.
Do not include .map files, because used only for debugging. Moreover, if you use hot replacement module, remove it to lighten vendor.

To pack for production, I personnaly use Webpack (and angular-cli relies on it too), because you can really configure everything for optimization or debugging.
If you want to use Webpack, I agree it is a bit tricky a first view, but see tutorials on the net, you won't be disappointed.
Else, use angular-cli, which get the job done really well.

Using Ahead-of-time compilation is mandatory to optimize apps, and shrink Angular 2 app to 250KB.

Here is a repo I created (github.com/JCornat/min-angular) to test minimal Angular bundle size, and I obtain 384kB. I am sure there is easy way to optimize it.

Talking about big apps, using the AngularClass/angular-starter configuration, the same as in the repo above, my bundle size for big apps (150+ components) went from 8MB (4MB without map files) to 580kB.

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

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

A generic solution like so

public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
        Function<Y, Z> function) {
    return input
            .entrySet()
            .stream()
            .collect(
                    Collectors.toMap((entry) -> entry.getKey(),
                            (entry) -> function.apply(entry.getValue())));
}

Example

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

JQuery addclass to selected div, remove class if another div is selected

I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:

            /* Add Class Heading*/
            $(document).ready(function() {
            $( document ).on( 'click', 'ul#items li', function () { 
            $('ul#items li').removeClass('active'); 
            $(this).addClass('active');
            });
            });

Sleep function in Windows, using C

MSDN: Header: Winbase.h (include Windows.h)

How to convert JSON to CSV format and store in a variable

Sometimes objects have different lengths. So I ran into the same problem as Kyle Pennell. But instead of sorting the array we simply traverse over it and pick the longest. Time complexity is reduced to O(n), compared to O(n log(n)) when sorting first.

I started with the code from Christian Landgren's updated ES6 (2016) version.

json2csv(json) {
    // you can skip this step if your input is a proper array anyways:
    const simpleArray = JSON.parse(json)
    // in array look for the object with most keys to use as header
    const header = simpleArray.map((x) => Object.keys(x))
      .reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []);

    // specify how you want to handle null values here
    const replacer = (key, value) => (
      value === undefined || value === null ? '' : value);
    let csv = simpleArray.map((row) => header.map(
      (fieldName) => JSON.stringify(row[fieldName], replacer)).join(','));
    csv = [header.join(','), ...csv];
    return csv.join('\r\n');
}

Combine two integer arrays

You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.

int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);

This will work regardless of the size of array1 and array2.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

Add arm64 to the target's valid architectures. Looks like it adds x86-64 architecture to simulator valid architectures as well.

Flask Download a File

To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.

Example:

from flask import Flask
from flask import send_file
app = Flask(__name__)

@app.route('/download')
def downloadFile ():
    #For windows you need to use drive name [ex: F:/Example.pdf]
    path = "/Examples.pdf"
    return send_file(path, as_attachment=True)

if __name__ == '__main__':
    app.run(port=5000,debug=True) 

Converting String to Double in Android

What about using the Double(String) constructor? So,

protein = new Double(p);

Don't know why it would be different, but might be worth a shot.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try like this,

jQuery('.leaderMultiSelctdropdown').select2('data');

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Check object empty

You can't do it directly, you should provide your own way to check this. Eg.

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.

CSS horizontal centering of a fixed div?

left: 50%;
margin-left: -400px; /* Half of the width */

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

@Before(JUnit4) -> @BeforeEach(JUnit5) - method is called before every test

@After(JUnit4) -> @AfterEach(JUnit5) - method is called after every test

@BeforeClass(JUnit4) -> @BeforeAll(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...

@AfterClass(JUnit4) -> @AfterAll(JUnit5) - static method is called after executing all tests in this class.

lexers vs parsers

To answer the question as asked (without repeating unduly what appears in other answers)

Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.

A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.

That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.

Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.

Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).

However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.

One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).

(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)

BNF is just a specific syntax for presenting CF grammars.

EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.

However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.

To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.

I would suggest also looking at AHR's answer.

But this leaves a question open: Why trees?

Trees are a good basis for specifying syntax because

  • they give a simple structure to the text

  • there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.

Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.

Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.

The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.

Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.

Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.

C# getting the path of %AppData%

You can also use

Environment.ExpandEnvironmentVariables("%AppData%\\DateLinks.xml");

to expand the %AppData% variable.

How to set the focus for a particular field in a Bootstrap modal, once it appears

I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript. The solution:

$('#myModal').on('shown.bs.modal', function () {
    setTimeout(function(){
        $('#inputId').focus();
    }, 100);
});

Probably it´s something about the animation!

Set focus on TextBox in WPF from view model

First off i would like to thank Avanka for helping me solve my focus problem. There is however a bug in the code he posted, namely in the line: if (e.OldValue == null)

The problem I had was that if you first click in your view and focus the control, e.oldValue is no longer null. Then when you set the variable to focus the control for the first time, this results in the lostfocus and gotfocus handlers not being set. My solution to this was as follows:

public static class ExtensionFocus
    {
    static ExtensionFocus()
        {
        BoundElements = new List<string>();
        }

    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
        typeof(ExtensionFocus), new FrameworkPropertyMetadata(false, IsFocusedChanged));

    private static List<string> BoundElements;

    public static bool? GetIsFocused(DependencyObject element)
        {
        if (element == null)
            {
            throw new ArgumentNullException("ExtensionFocus GetIsFocused called with null element");
            }
        return (bool?)element.GetValue(IsFocusedProperty);
        }

    public static void SetIsFocused(DependencyObject element, bool? value)
        {
        if (element == null)
            {
            throw new ArgumentNullException("ExtensionFocus SetIsFocused called with null element");
            }
        element.SetValue(IsFocusedProperty, value);
        }

    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        var fe = (FrameworkElement)d;

        // OLD LINE:
        // if (e.OldValue == null)
        // TWO NEW LINES:
        if (BoundElements.Contains(fe.Name) == false)
            {
            BoundElements.Add(fe.Name);
            fe.LostFocus += OnLostFocus;
            fe.GotFocus += OnGotFocus;
            }           


        if (!fe.IsVisible)
            {
            fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
            }

        if ((bool)e.NewValue)
            {
            fe.Focus();             
            }
        }

    private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
        var fe = (FrameworkElement)sender;

        if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
            {
            fe.IsVisibleChanged -= fe_IsVisibleChanged;
            fe.Focus();
            }
        }

    private static void OnLostFocus(object sender, RoutedEventArgs e)
        {
        if (sender != null && sender is Control s)
            {
            s.SetValue(IsFocusedProperty, false);
            }
        }

    private static void OnGotFocus(object sender, RoutedEventArgs e)
        {
        if (sender != null && sender is Control s)
            {
            s.SetValue(IsFocusedProperty, true);
            }
        }
    }

Difference between EXISTS and IN in SQL?

If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match.

Volley JsonObjectRequest Post request not working

All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Above answers are correct. This version is easy to follow:

Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:

Step [1] In your file which extends the RoomDatabase, change the line to:

`@Database(entities = ???.class,version = 1, exportSchema = true)`

Or

`@Database(entities = ???.class,version = 1)` 

(because the default value is always true)

Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:

         android{
                defaultConfig{
                      //javaComplieOptions SECTION
                      javaCompileOptions {
                            annotationProcessorOptions {
                                     arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
                            }
                       }
                      //Other SECTION
                      ...
                }
         }

$projectDir:is a variable name, you cannot change it. it will get your own project directory

schemas:is a string, you can change it to any you like. For example: "$projectDir/MyOwnSchemas".toString()

Hiding a password in a python script (insecure obfuscation only)

A way that I have done this is as follows:

At the python shell:

>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> print(key)
b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
>>> cipher = Fernet(key)
>>> password = "thepassword".encode('utf-8')
>>> token = cipher.encrypt(password)
>>> print(token)
b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

Then, create a module with the following code:

from cryptography.fernet import Fernet

# you store the key and the token
key = b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
token = b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

# create a cipher and decrypt when you need your password
cipher = Fernet(key)

mypassword = cipher.decrypt(token).decode('utf-8')

Once you've done this, you can either import mypassword directly or you can import the token and cipher to decrypt as needed.

Obviously, there are some shortcomings to this approach. If someone has both the token and the key (as they would if they have the script), they can decrypt easily. However it does obfuscate, and if you compile the code (with something like Nuitka) at least your password won't appear as plain text in a hex editor.

Omitting the second expression when using the if-else shorthand

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

Difference between getAttribute() and getParameter()

Another case when you should use .getParameter() is when forwarding with parameters in jsp:

<jsp:forward page="destination.jsp">
    <jsp:param name="userName" value="hamid"/>
</jsp:forward>

In destination.jsp, you can access userName like this:

request.getParameter("userName")

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

std::string to float or double

std::string num = "0.6";
double temp = ::atof(num.c_str());

Does it for me, it is a valid C++ syntax to convert a string to a double.

You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty.


Ahaha you have a Qt project ...

QString winOpacity("0.6");
double temp = winOpacity.toDouble();

Extra note:
If the input data is a const char*, QByteArray::toDouble will be faster.

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

How do I switch between command and insert mode in Vim?

This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.

WPF global exception handler

I use the following code in my WPF apps to show a "Sorry for the inconvenience" dialog box whenever an unhandled exception occurs. It shows the exception message, and asks user whether they want to close the app or ignore the exception and continue (the latter case is convenient when a non-fatal exceptions occur and user can still normally continue to use the app).

In App.xaml add the Startup event handler:

<Application .... Startup="Application_Startup">

In App.xaml.cs code add Startup event handler function that will register the global application event handler:

using System.Windows.Threading;

private void Application_Startup(object sender, StartupEventArgs e)
{
    // Global exception handling  
    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);    
}

void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{    
    \#if DEBUG   // In debug mode do not custom-handle the exception, let Visual Studio handle it

    e.Handled = false;

    \#else

    ShowUnhandledException(e);    

    \#endif     
}

void ShowUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true;

    string errorMessage = string.Format("An application error occurred.\nPlease check whether your data is correct and repeat the action. If this error occurs again there seems to be a more serious malfunction in the application, and you better close it.\n\nError: {0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)",

    e.Exception.Message + (e.Exception.InnerException != null ? "\n" + 
    e.Exception.InnerException.Message : null));

    if (MessageBox.Show(errorMessage, "Application Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)   {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
    {
        Application.Current.Shutdown();
    } 
}

ASP.NET Core return JSON with status code

The easiest way I came up with is :

var result = new Item { Id = 123, Name = "Hero" };

return new JsonResult(result)
{
    StatusCode = StatusCodes.Status201Created // Status code here 
};

Docker Compose wait for container X before starting Y

You can also solve this by setting an endpoint which waits for the service to be up by using netcat (using the docker-wait script). I like this approach as you still have a clean command section in your docker-compose.yml and you don't need to add docker specific code to your application:

version: '2'
services:
  db:
    image: postgres
  django:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    entrypoint: ./docker-entrypoint.sh db 5432
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

Then your docker-entrypoint.sh:

#!/bin/sh

postgres_host=$1
postgres_port=$2
shift 2
cmd="$@"

# wait for the postgres docker to be running
while ! nc $postgres_host $postgres_port; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done

>&2 echo "Postgres is up - executing command"

# run the command
exec $cmd

This is nowadays documented in the official docker documentation.

PS: You should install netcat in your docker instance if this is not available. To do so add this to your Docker file :

RUN apt-get update && apt-get install netcat-openbsd -y 

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  

Check this TUTORIAL for more details.

How do I uniquely identify computers visiting my web site?

Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.

I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.

Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).

A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.

Hope that helps.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

Center align a column in twitter bootstrap

The question is correctly answered here Center a column using Twitter Bootstrap 3

For odd rows: i.e., col-md-7 or col-large-9 use this

Add col-centered to the column you want centered.

<div class="col-lg-11 col-centered">    

And add this to your stylesheet:

.col-centered{
float: none;
margin: 0 auto;
}

For even rows: i.e., col-md-6 or col-large-10 use this

Simply use bootstrap 3's offset col class. i.e.,

<div class="col-lg-10 col-lg-offset-1">

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

.NET obfuscation tools/strategy

I had to use a obfuscation/resource protection in my latest rpoject and found Crypto Obfuscator as a nice and simple to use tool. The serialization issue is only a matter of settings in this tool.

How to remove all characters after a specific character in python?

The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:

mystring = "123?567"
mystring[ 0 : mystring.index("?")]

>> '123'

If you want to keep the character, add 1 to the character position.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.

Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.

Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.

In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.

If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.

Use jQuery to scroll to the bottom of a div with lots of text

please refer : .scrollTop(), You can give a try to the solution here : http://jsfiddle.net/y430ovjt/

_x000D_
_x000D_
$(function() {_x000D_
  var wtf    = $('#scroll');_x000D_
  var height = wtf[0].scrollHeight;_x000D_
  wtf.scrollTop(height);_x000D_
});
_x000D_
 #scroll {_x000D_
   width: 200px;_x000D_
   height: 300px;_x000D_
   overflow-y: scroll;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="scroll">_x000D_
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Edit : for the people who are looking for a nice little animation with scrolling : http://jsfiddle.net/o98zbx8j

_x000D_
_x000D_
$(function() {_x000D_
  var height = 0;_x000D_
_x000D_
  function scroll(height, ele) {_x000D_
    this.stop().animate({_x000D_
      scrollTop: height_x000D_
    }, 1000, function() {_x000D_
      var dir = height ? "top" : "bottom";_x000D_
      $(ele).html("scroll to " + dir).attr({_x000D_
        id: dir_x000D_
      });_x000D_
    });_x000D_
  };_x000D_
  var wtf = $('#scroll');_x000D_
  $("#bottom, #top").click(function() {_x000D_
    height = height < wtf[0].scrollHeight ? wtf[0].scrollHeight : 0;_x000D_
    scroll.call(wtf, height, this);_x000D_
  });_x000D_
});
_x000D_
#scroll {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  overflow-y: scroll;_x000D_
}_x000D_
#bottom,_x000D_
#top {_x000D_
  font-size: 12px;_x000D_
  cursor: pointer;_x000D_
  min-width: 50px;_x000D_
  padding: 5px;_x000D_
  border: 2px solid #0099f9;_x000D_
  border-radius: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="bottom">scroll to bottom</span>_x000D_
<br />_x000D_
<br />_x000D_
<br />_x000D_
<div id="scroll">_x000D_
  <center><b>There's Plenty of Room at the Top, seriously?</b>_x000D_
  </center>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at enim dignissim, eleifend eros at, lobortis sem. Mauris vel erat felis. Proin quis convallis neque, quis molestie augue. Vestibulum aliquam elit sit amet venenatis eleifend. Donec dapibus_x000D_
    mauris ac lorem mattis pulvinar. Curabitur cursus elit commodo tellus bibendum, ut euismod nisi luctus. Pellentesque id magna nunc. Nam luctus nisi sapien, ac porta sem ultrices vitae. Suspendisse aliquet eleifend nunc, in mattis tellus dapibus rutrum._x000D_
    Nullam a sem venenatis, suscipit lorem eu, facilisis leo. Nunc eget eleifend magna. Curabitur dictum dui in massa vestibulum sagittis. Mauris sodales neque at tincidunt feugiat. Curabitur iaculis purus nec tortor elementum pulvinar. Donec non mattis_x000D_
    augue.</p>_x000D_
_x000D_
  <p>Integer sit amet iaculis nulla. Cras vehicula nunc eu leo aliquet, et convallis erat aliquet. Aenean tempor faucibus justo, porta blandit felis semper at. Maecenas auctor nibh sit amet tellus consectetur, et varius velit iaculis. Phasellus convallis_x000D_
    lacinia dapibus. Praesent tempus nunc elit, id volutpat tellus sagittis commodo. Vestibulum ultrices quam vel congue viverra. Integer varius diam quis tempor consequat. Integer pulvinar neque lorem, eu lobortis augue pharetra vel. Praesent ornare_x000D_
    lacus quis nisi fermentum dignissim. Curabitur hendrerit augue eu interdum interdum.</p>_x000D_
_x000D_
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam a ex non dolor rutrum suscipit vitae sit amet nibh. Donec pulvinar odio non ultrices dignissim. Quisque in risus lobortis, accumsan ante et, pellentesque_x000D_
    erat. Quisque ultricies tortor sed tortor venenatis posuere. Integer convallis nunc ut tellus sagittis, et imperdiet erat volutpat. Sed non maximus augue. Sed mattis ipsum sed sem rutrum, at mollis ligula facilisis. Etiam fringilla hendrerit mi eu_x000D_
    molestie. Etiam semper feugiat nunc, eu pellentesque metus porta pretium. Duis tempor neque ut libero scelerisque euismod. Vivamus molestie, quam a mattis scelerisque, dolor turpis accumsan quam, a cursus sem quam at ex. Suspendisse congue elit quis_x000D_
    sem scelerisque commodo.</p>_x000D_
_x000D_
  <p>Ut eu odio at urna hendrerit ullamcorper. Nulla ut turpis molestie diam aliquet luctus. Curabitur dignissim tellus ut porta sagittis. Vivamus ut erat ut neque consequat interdum. Duis vitae risus eget arcu pulvinar venenatis. Maecenas erat arcu, hendrerit_x000D_
    id tortor ut, viverra elementum nibh. Nam quis metus sit amet lacus rhoncus porttitor ac non ipsum. Nullam lacus dui, tempus sed elementum ut, venenatis eget ipsum. Quisque blandit maximus enim eu porta.</p>_x000D_
_x000D_
  <p>Donec mollis diam eros, eu ultrices magna sollicitudin vitae. Nullam quam sapien, elementum a metus nec, facilisis scelerisque nulla. Praesent lobortis nisi ac leo laoreet, quis molestie ipsum porta. Suspendisse aliquet in velit eu ullamcorper. Maecenas_x000D_
    auctor, mi ut viverra elementum, metus turpis commodo orci, eu commodo erat dolor malesuada arcu. Fusce condimentum augue</p>_x000D_
  <center><b>Voila!! You have reached the bottom, already! :)</b>_x000D_
  </center>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

Curl Command to Repeat URL Request

for i in `seq 1 20`; do curl http://url; done

Or if you want to get timing information back, use ab:

ab -n 20 http://url/

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

FFmpeg on Android

I had the same issue, I found most of the answers here out dated. I ended up writing a wrapper on FFMPEG to access from Android with a single line of code.

https://github.com/madhavanmalolan/ffmpegandroidlibrary

Using SSH keys inside docker container

In a running docker container, you can issue ssh-keygen with the docker -i (interactive) option. This will forward the container prompts to create the key inside the docker container.

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.

btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.

tsql returning a table from a function or store procedure

You need a special type of function known as a table valued function. Below is a somewhat long-winded example that builds a date dimension for a data warehouse. Note the returns clause that defines a table structure. You can insert anything into the table variable (@DateHierarchy in this case) that you want, including building a temporary table and copying the contents into it.

if object_id ('ods.uf_DateHierarchy') is not null
    drop function ods.uf_DateHierarchy
go

create function ods.uf_DateHierarchy (
       @DateFrom datetime
      ,@DateTo   datetime
) returns @DateHierarchy table (
        DateKey           datetime
       ,DisplayDate       varchar (20)
       ,SemanticDate      datetime
       ,MonthKey          int     
       ,DisplayMonth      varchar (10)
       ,FirstDayOfMonth   datetime
       ,QuarterKey        int
       ,DisplayQuarter    varchar (10)
       ,FirstDayOfQuarter datetime
       ,YearKey           int
       ,DisplayYear       varchar (10)
       ,FirstDayOfYear    datetime
) as begin
    declare @year            int
           ,@quarter         int
           ,@month           int
           ,@day             int
           ,@m1ofqtr         int
           ,@DisplayDate     varchar (20)
           ,@DisplayQuarter  varchar (10)
           ,@DisplayMonth    varchar (10)
           ,@DisplayYear     varchar (10)
           ,@today           datetime
           ,@MonthKey        int
           ,@QuarterKey      int
           ,@YearKey         int
           ,@SemanticDate    datetime
           ,@FirstOfMonth    datetime
           ,@FirstOfQuarter  datetime
           ,@FirstOfYear     datetime
           ,@MStr            varchar (2)
           ,@QStr            varchar (2)
           ,@Ystr            varchar (4)
           ,@DStr            varchar (2)
           ,@DateStr         varchar (10)


    -- === Previous ===================================================
    -- Special placeholder date of 1/1/1800 used to denote 'previous'
    -- so that naive date calculations sort and compare in a sensible
    -- order.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '1800-01-01'
        ,'Previous'
        ,'1800-01-01'
        ,180001
        ,'Prev'
        ,'1800-01-01'
        ,18001
        ,'Prev'
        ,'1800-01-01'
        ,1800
        ,'Prev'
        ,'1800-01-01'
    )

    -- === Calendar Dates =============================================
    -- These are generated from the date range specified in the input
    -- parameters.
    --
    set @today = @Datefrom
    while @today <= @DateTo begin

        set @year = datepart (yyyy, @today)
        set @month = datepart (mm, @today)
        set @day = datepart (dd, @today)
        set @quarter = case when @month in (1,2,3) then 1
                            when @month in (4,5,6) then 2
                            when @month in (7,8,9) then 3
                            when @month in (10,11,12) then 4
                        end
        set @m1ofqtr = @quarter * 3 - 2 

        set @DisplayDate = left (convert (varchar, @today, 113), 11)
        set @SemanticDate = @today
        set @MonthKey = @year * 100 + @month
        set @DisplayMonth = substring (convert (varchar, @today, 113), 4, 8)
        set @Mstr = right ('0' + convert (varchar, @month), 2)
        set @Dstr = right ('0' + convert (varchar, @day), 2)
        set @Ystr = convert (varchar, @year)
        set @DateStr = @Ystr + '-' + @Mstr + '-01'
        set @FirstOfMonth = convert (datetime, @DateStr, 120)
        set @QuarterKey = @year * 10 + @quarter
        set @DisplayQuarter = 'Q' + convert (varchar, @quarter) + ' ' +
                                    convert (varchar, @year)
        set @QStr = right ('0' + convert (varchar, @m1ofqtr), 2)   
        set @DateStr = @Ystr + '-' + @Qstr + '-01' 
        set @FirstOfQuarter = convert (datetime, @DateStr, 120)
        set @YearKey = @year
        set @DisplayYear = convert (varchar, @year)
        set @DateStr = @Ystr + '-01-01'
        set @FirstOfYear = convert (datetime, @DateStr)


        insert @DateHierarchy (
             DateKey
            ,DisplayDate
            ,SemanticDate
            ,MonthKey
            ,DisplayMonth
            ,FirstDayOfMonth
            ,QuarterKey
            ,DisplayQuarter
            ,FirstDayOfQuarter
            ,YearKey
            ,DisplayYear
            ,FirstDayOfYear
        ) values (
             @today
            ,@DisplayDate
            ,@SemanticDate
            ,@Monthkey
            ,@DisplayMonth
            ,@FirstOfMonth
            ,@QuarterKey
            ,@DisplayQuarter
            ,@FirstOfQuarter
            ,@YearKey
            ,@DisplayYear
            ,@FirstOfYear
        )

        set @today = dateadd (dd, 1, @today)
    end

    -- === Specials ===================================================
    -- 'Ongoing', 'Error' and 'Not Recorded' set two years apart to
    -- avoid accidental collisions on 'Next Year' calculations.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9000-01-01'
        ,'Ongoing'
        ,'9000-01-01'
        ,900001
        ,'Ong.'
        ,'9000-01-01'
        ,90001
        ,'Ong.'
        ,'9000-01-01'
        ,9000
        ,'Ong.'
        ,'9000-01-01'
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9100-01-01'
        ,'Error'
        ,null
        ,910001
        ,'Error'
        ,null
        ,91001
        ,'Error'
        ,null
        ,9100
        ,'Err'
        ,null
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9200-01-01'
        ,'Not Recorded'
        ,null
        ,920001
        ,'N/R'
        ,null
        ,92001
        ,'N/R'
        ,null
        ,9200
        ,'N/R'
        ,null
    )

    return
end

go

Regex to match 2 digits, optional decimal, two digits

A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$

grep output to show only matching file

Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *

Angularjs $http.get().then and binding to a list

Try using the success() call back

$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
    $scope.Documents = result;
});

But now since Documents is an array and not a promise, remove the ()

<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
           <input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
        </span>
 <span>{{document.Name}}</span>

</li>

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

How to checkout in Git by date?

In my case the -n 1 option doesn't work. On Windows I've found that the following sequence of commands works fine:

git rev-list -1 --before="2012-01-15 12:00" master

This returns the appropriate commit's SHA for the given date, and then:

git checkout SHA

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

SQL Plus change current directory

Years later i had the same problem. My solution is the creation of a temporary batchfile and another instance of sqlplus:

In first SQL-Script:

:
set echo off
spool sqlsub_tmp.bat
prompt cd /D D:\some\dir
prompt sqlplus user/passwd@tnsname @second_script.sql
spool off
host sqlsub_tmp.bat
host del sqlsub_tmp.bat
:

Note that "second_script.sql" needs an "exit" statement at end if you want to return to the first one..

Test process.env with Jest

You can use the setupFiles feature of the Jest configuration. As the documentation said that,

A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

  1. npm install dotenv dotenv that uses to access environment variable.

  2. Create your .env file to the root directory of your application and add this line into it:

    #.env
    APP_PORT=8080
    
  3. Create your custom module file as its name being someModuleForTest.js and add this line into it:

    // someModuleForTest.js
    require("dotenv").config()
    
  4. Update your jest.config.js file like this:

    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
  5. You can access an environment variable within all test blocks.

    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    

Why should I use a pointer rather than the object itself?

Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.

Another thing you mentioned in your question:

Object *myObject = new Object;

How does it work? It creates pointer of Object type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new), you also have to free memory manually, that means in code you should have:

delete myObject;

This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.


And now some introduction is over and go back to question.

You can use pointers instead of objects to get better performance while transferring data between function.

Take a look, you have std::string (it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...) which can be declarated in different ways:

  1. void foo(std::string xml); In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.
  2. void foo(std::string* xml); In this case you will pass pointer to object, same speed as passing size_t variable, however this declaration has error prone, because you can pass NULL pointer or invalid pointer. Pointers usually used in C because it doesn't have references.
  3. void foo(std::string& xml); Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).
  4. void foo(const std::string* xml); Here is the same as second, just pointer value cannot be changed.
  5. void foo(const std::string& xml); Here is the same as third, but object value cannot be changed.

What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new or regular).


Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string is also container, some guys forgot it :)

Docker CE on RHEL - Requires: container-selinux >= 2.9

Just install selinux latest version to fix it:
sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

More versions at http://mirror.centos.org/centos/7/extras/x86_64/Packages/

Older versions of 2.9: http://ftp.riken.jp/Linux/cern/centos/7/extras/x86_64/Packages/

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

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

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

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

To access branch1 text you would use:

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

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

How to detect if multiple keys are pressed at once using JavaScript?

I like to use this snippet, its very useful for writing game input scripts

var keyMap = [];

window.addEventListener('keydown', (e)=>{
    if(!keyMap.includes(e.keyCode)){
        keyMap.push(e.keyCode);
    }
})

window.addEventListener('keyup', (e)=>{
    if(keyMap.includes(e.keyCode)){
        keyMap.splice(keyMap.indexOf(e.keyCode), 1);
    }
})

function key(x){
    return (keyMap.includes(x));
}

function checkGameKeys(){
    if(key(32)){
        // Space Key
    }
    if(key(37)){
        // Left Arrow Key
    }
    if(key(39)){
        // Right Arrow Key
    }
    if(key(38)){
        // Up Arrow Key
    }
    if(key(40)){
        // Down Arrow Key
    }
    if(key(65)){
        // A Key
    }
    if(key(68)){
        // D Key
    }
    if(key(87)){
        // W Key
    }
    if(key(83)){
        // S Key
    }
}

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

Java foreach loop: for (Integer i : list) { ... }

The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:

  if(x.isEmpty()) return;
  int last = x.size() - 1;
  for(Integer i : x.subList(0, last)) out.println(i);
  out.println("last " + x.get(last));

This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).

Static methods in Python?

You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

Mostly, you just use functions though...

shuffling/permutating a DataFrame in pandas

In [16]: def shuffle(df, n=1, axis=0):     
    ...:     df = df.copy()
    ...:     for _ in range(n):
    ...:         df.apply(np.random.shuffle, axis=axis)
    ...:     return df
    ...:     

In [17]: df = pd.DataFrame({'A':range(10), 'B':range(10)})

In [18]: shuffle(df)

In [19]: df
Out[19]: 
   A  B
0  8  5
1  1  7
2  7  3
3  6  2
4  3  4
5  0  1
6  9  0
7  4  6
8  2  8
9  5  9

Redraw datatables after using ajax to refresh the table content?

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.

Binding to static property

Another solution is to create a normal class which implements PropertyChanger like this

public class ViewProps : PropertyChanger
{
    private string _MyValue = string.Empty;
    public string MyValue
    {
        get { 
            return _MyValue
        }
        set
        {
            if (_MyValue == value)
            {
                return;
            }
            SetProperty(ref _MyValue, value);
        }
    }
}

Then create a static instance of the class somewhere you wont

public class MyClass
{
    private static ViewProps _ViewProps = null;
    public static ViewProps ViewProps
    {
        get
        {
            if (_ViewProps == null)
            {
                _ViewProps = new ViewProps();
            }
            return _ViewProps;
        }
    }
}

And now use it as static property

<TextBlock  Text="{x:Bind local:MyClass.ViewProps.MyValue, Mode=OneWay}"  />

And here is PropertyChanger implementation if necessary

public abstract class PropertyChanger : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

How to get URI from an asset File?

Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }

CSS blur on background image but not on content

Add another div or img to your main div and blur that instead. jsfiddle

.blur {
    background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
    background-size:cover;
    -webkit-filter: blur(13px);
    -moz-filter: blur(13px);
    -o-filter: blur(13px);
    -ms-filter: blur(13px);
    filter: blur(13px);
    position:absolute;
    width:100%;
    height:100%;
}

How to match hyphens with Regular Expression?

Is this what you are after?

MatchCollection matches = Regex.Matches(mystring, "-");

Chart.js canvas resize

I had a similar problem and found your answer.. I eventually came to a solution.

It looks like the source of Chart.js has the following(presumably because it is not supposed to re-render and entirely different graph in the same canvas):

    //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
if (window.devicePixelRatio) {
    context.canvas.style.width = width + "px";
    context.canvas.style.height = height + "px";
    context.canvas.height = height * window.devicePixelRatio;
    context.canvas.width = width * window.devicePixelRatio;
    context.scale(window.devicePixelRatio, window.devicePixelRatio);
}

This is fine if it is called once, but when you redraw multiple times you end up changing the size of the canvas DOM element multiple times causing re-size.

Hope that helps!

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

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

there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.

Create PostgreSQL ROLE (user) if it doesn't exist

The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

Workaround from within psql

SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec

Workaround from the shell

echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql

See accepted answer there for more details.

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

What should be the package name of android app?

As stated here: Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:

enter image description here

UITableView example for Swift

In Swift 4.1 and Xcode 9.4.1

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

If you are using storyboard, no need for Step 3.

But you need to create IBOutlet for your table view before Step 4.

Can "git pull --all" update all my local branches?

There are plenty of acceptable answers here, but some of the plumbing may be be a little opaque to the uninitiated. Here's a much simpler example that can easily be customized:

$ cat ~/bin/git/git-update-all
#!/bin/bash
# Update all local branches, checking out each branch in succession.
# Eventually returns to the original branch. Use "-n" for dry-run.
git_update_all() {
  local run br
  br=$(git name-rev --name-only HEAD 2>/dev/null)
  [ "$1" = "-n" ] && shift && run=echo

  for x in $( git branch | cut -c3- ) ; do
     $run git checkout $x && $run git pull --ff-only || return 2
  done

  [ ${#br} -gt 0 ] && $run git checkout "$br"
}

git_update_all "$@"

If you add ~/bin/git to your PATH (assuming the file is ~/bin/git/git-update-all), you can just run:

$ git update-all

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate an END (or PAGE_DOWN) key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)

How to generate a random integer number from within a range

For those who understand the bias problem but can't stand the unpredictable run-time of rejection-based methods, this series produces a progressively less biased random integer in the [0, n-1] interval:

r = n / 2;
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
...

It does so by synthesising a high-precision fixed-point random number of i * log_2(RAND_MAX + 1) bits (where i is the number of iterations) and performing a long multiplication by n.

When the number of bits is sufficiently large compared to n, the bias becomes immeasurably small.

It does not matter if RAND_MAX + 1 is less than n (as in this question), or if it is not a power of two, but care must be taken to avoid integer overflow if RAND_MAX * n is large.

Entity Framework 5 Updating a Record

Depending on your use case, all the above solutions apply. This is how i usually do it however :

For server side code (e.g. a batch process) I usually load the entities and work with dynamic proxies. Usually in batch processes you need to load the data anyways at the time the service runs. I try to batch load the data instead of using the find method to save some time. Depending on the process I use optimistic or pessimistic concurrency control (I always use optimistic except for parallel execution scenarios where I need to lock some records with plain sql statements, this is rare though). Depending on the code and scenario the impact can be reduced to almost zero.

For client side scenarios, you have a few options

  1. Use view models. The models should have a property UpdateStatus(unmodified-inserted-updated-deleted). It is the responsibility of the client to set the correct value to this column depending on the user actions (insert-update-delete). The server can either query the db for the original values or the client should send the original values to the server along with the changed rows. The server should attach the original values and use the UpdateStatus column for each row to decide how to handle the new values. In this scenario I always use optimistic concurrency. This will only do the insert - update - delete statements and not any selects, but it might need some clever code to walk the graph and update the entities (depends on your scenario - application). A mapper can help but does not handle the CRUD logic

  2. Use a library like breeze.js that hides most of this complexity (as described in 1) and try to fit it to your use case.

Hope it helps

Select folder dialog WPF

MVVM + WinForms FolderBrowserDialog as behavior

public class FolderDialogBehavior : Behavior<Button>
{
    public string SetterName { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
    }

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK && AssociatedObject.DataContext != null)
        {
            var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p => p.CanRead && p.CanWrite)
            .Where(p => p.Name.Equals(SetterName))
            .First();

            propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
        }
    }
}

Usage

     <Button Grid.Column="3" Content="...">
            <Interactivity:Interaction.Behaviors>
                <Behavior:FolderDialogBehavior SetterName="SomeFolderPathPropertyName"/>
            </Interactivity:Interaction.Behaviors>
     </Button>

Blogpost: http://kostylizm.blogspot.ru/2014/03/wpf-mvvm-and-winforms-folder-dialog-how.html

docker mounting volumes on host

This is from the Docker documentation itself, might be of help, simple and plain:

"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ G2        : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

How to disable an input box using angular.js

<input data-ng-model="userInf.username"  class="span12 editEmail" type="text"  placeholder="[email protected]"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>

jQuery return ajax result into outside variable

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

Proper syntax for the Axios call would actually look like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});

How to split page into 4 equal parts?

Some good answers here but just adding an approach that won't be affected by borders and padding:

<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>

<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>

Typescript empty object for a typed variable

you can do this as below in typescript

 const _params = {} as any;

 _params.name ='nazeh abel'

since typescript does not behave like javascript so we have to make the type as any otherwise it won't allow you to assign property dynamically to an object

jQuery find element by data attribute value

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

_x000D_
_x000D_
$(function() {_x000D_
  $('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
  background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
_x000D_
_x000D_

C++ Loop through Map

As P0W has provided complete syntax for each C++ version, I would like to add couple of more points by looking at your code

  • Always take const & as argument as to avoid extra copies of the same object.
  • use unordered_map as its always faster to use. See this discussion

here is a sample code:

#include <iostream>
#include <unordered_map>
using namespace std;

void output(const auto& table)
{
   for (auto const & [k, v] : table)
   {
        std::cout << "Key: " << k << " Value: " << v << std::endl;
   }
}

int main() {
    std::unordered_map<string, int> mydata = {
        {"one", 1},
        {"two", 2},
        {"three", 3}
    };
    output(mydata);
    return 0;
}

Sanitizing strings to make them URL and filename safe?

I don't think having a list of chars to remove is safe. I would rather use the following:

For filenames: Use an internal ID or a hash of the filecontent. Save the document name in a database. This way you can keep the original filename and still find the file.

For url parameters: Use urlencode() to encode any special characters.

How can I convert String to Int?

This code works for me in Visual Studio 2010:

int someValue = Convert.ToInt32(TextBoxD1.Text);

Global keyboard capture in C# application

Here's my code that works:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace SnagFree.TrayApp.Core
{
    class GlobalKeyboardHookEventArgs : HandledEventArgs
    {
        public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
        public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

        public GlobalKeyboardHookEventArgs(
            GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
            GlobalKeyboardHook.KeyboardState keyboardState)
        {
            KeyboardData = keyboardData;
            KeyboardState = keyboardState;
        }
    }

    //Based on https://gist.github.com/Stasonix
    class GlobalKeyboardHook : IDisposable
    {
        public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

        public GlobalKeyboardHook()
        {
            _windowsHookHandle = IntPtr.Zero;
            _user32LibraryHandle = IntPtr.Zero;
            _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

            _user32LibraryHandle = LoadLibrary("User32");
            if (_user32LibraryHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }



            _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
            if (_windowsHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // because we can unhook only in the same thread, not in garbage collector thread
                if (_windowsHookHandle != IntPtr.Zero)
                {
                    if (!UnhookWindowsHookEx(_windowsHookHandle))
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                    }
                    _windowsHookHandle = IntPtr.Zero;

                    // ReSharper disable once DelegateSubtraction
                    _hookProc -= LowLevelKeyboardProc;
                }
            }

            if (_user32LibraryHandle != IntPtr.Zero)
            {
                if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _user32LibraryHandle = IntPtr.Zero;
            }
        }

        ~GlobalKeyboardHook()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private IntPtr _windowsHookHandle;
        private IntPtr _user32LibraryHandle;
        private HookProc _hookProc;

        delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);

        /// <summary>
        /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
        /// You would install a hook procedure to monitor the system for certain types of events. These events are
        /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
        /// </summary>
        /// <param name="idHook">hook type</param>
        /// <param name="lpfn">hook procedure</param>
        /// <param name="hMod">handle to application instance</param>
        /// <param name="dwThreadId">thread identifier</param>
        /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

        /// <summary>
        /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
        /// </summary>
        /// <param name="hhk">handle to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        public static extern bool UnhookWindowsHookEx(IntPtr hHook);

        /// <summary>
        /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
        /// A hook procedure can call this function either before or after processing the hook information.
        /// </summary>
        /// <param name="hHook">handle to current hook</param>
        /// <param name="code">hook code passed to hook procedure</param>
        /// <param name="wParam">value passed to hook procedure</param>
        /// <param name="lParam">value passed to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        public struct LowLevelKeyboardInputEvent
        {
            /// <summary>
            /// A virtual-key code. The code must be a value in the range 1 to 254.
            /// </summary>
            public int VirtualCode;

            /// <summary>
            /// A hardware scan code for the key. 
            /// </summary>
            public int HardwareScanCode;

            /// <summary>
            /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
            /// </summary>
            public int Flags;

            /// <summary>
            /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
            /// </summary>
            public int TimeStamp;

            /// <summary>
            /// Additional information associated with the message. 
            /// </summary>
            public IntPtr AdditionalInformation;
        }

        public const int WH_KEYBOARD_LL = 13;
        //const int HC_ACTION = 0;

        public enum KeyboardState
        {
            KeyDown = 0x0100,
            KeyUp = 0x0101,
            SysKeyDown = 0x0104,
            SysKeyUp = 0x0105
        }

        public const int VkSnapshot = 0x2c;
        //const int VkLwin = 0x5b;
        //const int VkRwin = 0x5c;
        //const int VkTab = 0x09;
        //const int VkEscape = 0x18;
        //const int VkControl = 0x11;
        const int KfAltdown = 0x2000;
        public const int LlkhfAltdown = (KfAltdown >> 8);

        public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            bool fEatKeyStroke = false;

            var wparamTyped = wParam.ToInt32();
            if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
            {
                object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
                LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

                var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }

            return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
        }
    }
}

Usage:

using System;
using System.Windows.Forms;

namespace SnagFree.TrayApp.Core
{
    internal class Controller : IDisposable
    {
        private GlobalKeyboardHook _globalKeyboardHook;

        public void SetupKeyboardHooks()
        {
            _globalKeyboardHook = new GlobalKeyboardHook();
            _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
        }

        private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
        {
            //Debug.WriteLine(e.KeyboardData.VirtualCode);

            if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
                return;

            // seems, not needed in the life.
            //if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown &&
            //    e.KeyboardData.Flags == GlobalKeyboardHook.LlkhfAltdown)
            //{
            //    MessageBox.Show("Alt + Print Screen");
            //    e.Handled = true;
            //}
            //else

            if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
            {
                MessageBox.Show("Print Screen");
                e.Handled = true;
            }
        }

        public void Dispose()
        {
            _globalKeyboardHook?.Dispose();
        }
    }
}

.htaccess not working apache

First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.

Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.

Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.

Cannot instantiate the type List<Product>

Use a concrete list type, e.g. ArrayList instead of just List.

How to write to Console.Out during execution of an MSTest test

I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

The disposable ConsoleRedirector is defined as:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

iOS - Calling App Delegate method from ViewController

You can add #define uAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate] in your project's Prefix.pch file and then call any method of your AppDelegate in any UIViewController with the below code.

[uAppDelegate showLoginView];

from list of integers, get number closest to a given value

def closest(list, Number):
    aux = []
    for valor in list:
        aux.append(abs(Number-valor))

    return aux.index(min(aux))

This code will give you the index of the closest number of Number in the list.

The solution given by KennyTM is the best overall, but in the cases you cannot use it (like brython), this function will do the work

What is the lifetime of a static variable in a C++ function?

The Static variables are come into play once the program execution starts and it remain available till the program execution ends.

The Static variables are created in the Data Segment of the Memory.

Gradle does not find tools.jar

On windows 10, I encounter the same problem and this how I fixed the issue;

  1. Access Advance System Settings>Environment Variables>System Variables
  2. Select PATH overwrite the default C:\ProgramData\Oracle\Java\javapath
  3. With your own jdk installation that is JAVA_HOME=C:\Program Files\Java\jdk1.8.0_162

Display date/time in user's locale format and time offset

Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

How to get first record in each group using Linq

The awnser of @Alireza is totally correct, but you must notice that when using this code

var res = from element in list
          group element by element.F1
              into groups
              select groups.OrderBy(p => p.F2).First();

which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups

var res = (from element in list)
          .OrderBy(x => x.F2)
          .GroupBy(x => x.F1)
          .Select()

Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow

 var res = (from element in list)
          .GroupBy(x => x.F1)
          .Select(y => new
           {
             F1 = y.FirstOrDefault().F1;
             F2 = y.First().F2;
             F3 = y.Last().F3;
           });

So you will get something like

   F1            F2             F3 
 -----------------------------------
   Nima          1990           12
   John          2001           2
   Sara          2010           4

How can I avoid ResultSet is closed exception in Java?

You may have closed either the Connection or Statement that made the ResultSet, which would lead to the ResultSet being closed as well.

How to get terminal's Character Encoding

To see the current locale information use locale command. Below is an example on RHEL 7.8

[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

android edittext onchange listener

TextWatcher didn't work for me as it kept firing for every EditText and messing up each others values.

Here is my solution:

public class ConsultantTSView extends Activity {
    .....

    //Submit is called when I push submit button.
    //I wanted to retrieve all EditText(tsHours) values in my HoursList

    public void submit(View view){

        ListView TSDateListView = (ListView) findViewById(R.id.hoursList);
        String value = ((EditText) TSDateListView.getChildAt(0).findViewById(R.id.tsHours)).getText().toString();
    }
}

Hence by using the getChildAt(xx) method you can retrieve any item in the ListView and get the individual item using findViewById. And it will then give the most recent value.

Check whether a variable is a string in Ruby

In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.

  • o.class class of o.
  • o.instance_of? c determines whether o.class == c
  • o.is_a? c Is o an instance of c or any of it's subclasses?
  • o.kind_of? c synonym for *is_a?*
  • c === o for a class or module, determine if *o.is_a? c* (String === "s" returns true)

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

Calling a Javascript Function from Console

This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here

Error 500: Premature end of script headers

I have this issue and resolve this by changing PHP version from 5.3.3 to 5.6.30.

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

How to vertically align label and input in Bootstrap 3?

I'm sure you've found your answer by now, but for those who are still looking for an answer:

When input-lg is used, margins mismatch unless you use form-group-lg in addition to form-group class. Its example is in docs:

<form class="form-horizontal">
  <div class="form-group form-group-lg">
    <label class="col-sm-2 control-label" for="formGroupInputLarge">Large label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputLarge" placeholder="Large input">
    </div>
  </div>
  <div class="form-group form-group-sm">
    <label class="col-sm-2 control-label" for="formGroupInputSmall">Small label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputSmall" placeholder="Small input">
    </div>
  </div>
</form>

Truncate number to two decimal places without rounding

Taking the knowledge from all the previous answers combined,

this is what I came up with as a solution:

function toFixedWithoutRounding(num, fractionDigits) {
  if ((num > 0 && num < 0.000001) || (num < 0 && num > -0.000001)) {
    // HACK: below this js starts to turn numbers into exponential form like 1e-7.
    // This gives wrong results so we are just changing the original number to 0 here
    // as we don't need such small numbers anyway.
    num = 0;
  }
  const re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fractionDigits || -1) + '})?');
  return Number(num.toString().match(re)[0]).toFixed(fractionDigits);
}

Dictionary of dictionaries in Python?

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

Python date string to date object

you have a date string like this, "24052010" and you want date object for this,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

this cus_date will give you date object.

you can retrieve date string from your date object using this,

cus_date.strftime("%d%m%Y")

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

VB.Net: Dynamically Select Image from My.Resources

Sometimes you must change the name (or check to get it automatically from compiler).

Example:

Filename = amp2-rot.png

It is not working as:

PictureBoxName.Image = resources.GetObject("amp2-rot.png")

It works, just as amp2_rot for me:

 PictureBox_L1.Image = My.Resources.Resource.amp2_rot

How to set environment via `ng serve` in Angular 6

This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve ones.

So just to leave no confusions:

  1. --env is not supported in angular 6
  2. --env got changed into --configuration || -c (and is now more powerful)
  3. to manage various envs, in addition to adding new environment file, it is now required to do some changes in angular.json file:
    • add new configuration in the build { ... "build": "configurations": ... property
    • new build configuration may contain only fileReplacements part, (but more options are available)
    • add new configuration in the serve { ... "serve": "configurations": ... property
    • new serve configuration shall contain of browserTarget="your-project-name:build:staging"

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Why does jQuery or a DOM method such as getElementById not find the element?

This solution is for the people who don't use jQuery and to improve performance by not moving the script to bottom of the page, and the problem is that the script is loaded before the html elements are loaded. Add your code in this function body

window.onload=()=>{
    
    // your code here

    // example
    let element=document.getElementById("elementId");
    console.log(element);

};

add everything that has to work only after the document is loaded and keep other functions that has to be executed as soon as the script is loaded outside the function.

I recommend this method instead of moving down the script, because if the script is on top, the browser will try to download it as soon as it sees the script tag, if it is on the bottom of the page, it will take some more time to load it and until that time no event listeners in the script will work. in this case all other functions could be called and the window.onload will get called once everything is loaded.

How to open a website when a Button is clicked in Android application?

If you are talking about an RCP app, then what you need is the SWT link widget.

Here is the official link event handler snippet.

Update

Here is minimalist android application to connect to either superuser or stackoverflow with 2 buttons.

package ap.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class LinkButtons extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void goToSo (View view) {
        goToUrl ( "http://stackoverflow.com/");
    }

    public void goToSu (View view) {
        goToUrl ( "http://superuser.com/");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

}

And here is the layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/select" />
    <Button android:layout_height="wrap_content" android:clickable="true" android:autoLink="web" android:cursorVisible="true" android:layout_width="match_parent" android:id="@+id/button_so" android:text="StackOverflow" android:linksClickable="true" android:onClick="goToSo"></Button>
    <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"></Button>
</LinearLayout>

How to get the size of a JavaScript object?

If you need to programatically check for aprox. size of objects you can also check this library http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/ that I have been able to use for objects size.

Otherwise I suggest to use the Chrome/Firefox Heap Profiler.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As others have stated, regular (traditional) functions use this from the object that called the function, (e.g. a button that was clicked). Instead, arrow functions use this from the object that defines the function.

Consider two almost identical functions:

regular = function() {
  ' Identical Part Here;
}


arrow = () => {
  ' Identical Part Here;
}

The snippet below demonstrates the fundamental difference between what this represents for each function. The regular function outputs [object HTMLButtonElement] whereas the arrow function outputs [object Window].

_x000D_
_x000D_
<html>_x000D_
 <button id="btn1">Regular: `this` comes from "this button"</button>_x000D_
 <br><br>_x000D_
 <button id="btn2">Arrow: `this` comes from object that defines the function</button>_x000D_
 <p id="res"/>_x000D_
_x000D_
 <script>_x000D_
  regular = function() {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  arrow = () => {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  document.getElementById("btn1").addEventListener("click", regular);_x000D_
  document.getElementById("btn2").addEventListener("click", arrow);_x000D_
 </script>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

How to negate a method reference predicate

Building on other's answers and personal experience:

Predicate<String> blank = String::isEmpty;
content.stream()
       .filter(blank.negate())

Multiple queries executed in java in single statement

I was wondering if it is possible to execute something like this using JDBC.

"SELECT FROM * TABLE;INSERT INTO TABLE;"

Yes it is possible. There are two ways, as far as I know. They are

  1. By setting database connection property to allow multiple queries, separated by a semi-colon by default.
  2. By calling a stored procedure that returns cursors implicit.

Following examples demonstrate the above two possibilities.

Example 1: ( To allow multiple queries ):

While sending a connection request, you need to append a connection property allowMultiQueries=true to the database url. This is additional connection property to those if already exists some, like autoReConnect=true, etc.. Acceptable values for allowMultiQueries property are true, false, yes, and no. Any other value is rejected at runtime with an SQLException.

String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";  

Unless such instruction is passed, an SQLException is thrown.

You have to use execute( String sql ) or its other variants to fetch results of the query execution.

boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );

To iterate through and process results you require following steps:

READING_QUERY_RESULTS: // label  
    while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {  
        if ( hasMoreResultSets ) {  
            Resultset rs = stmt.getResultSet();
            // handle your rs here
        } // if has rs
        else { // if ddl/dml/...
            int queryResult = stmt.getUpdateCount();  
            if ( queryResult == -1 ) { // no more queries processed  
                break READING_QUERY_RESULTS;  
            } // no more queries processed  
            // handle success, failure, generated keys, etc here
        } // if ddl/dml/...

        // check to continue in the loop  
        hasMoreResultSets = stmt.getMoreResults();  
    } // while results

Example 2: Steps to follow:

  1. Create a procedure with one or more select, and DML queries.
  2. Call it from java using CallableStatement.
  3. You can capture multiple ResultSets executed in procedure.
    DML results can't be captured but can issue another select
    to find how the rows are affected in the table.

Sample table and procedure:

mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)

mysql> delimiter //
mysql> create procedure multi_query()
    -> begin
    ->  select count(*) as name_count from tbl_mq;
    ->  insert into tbl_mq( names ) values ( 'ravi' );
    ->  select last_insert_id();
    ->  select * from tbl_mq;
    -> end;
    -> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
|          0 |
+------------+
1 row in set (0.00 sec)

+------------------+
| last_insert_id() |
+------------------+
|                3 |
+------------------+
1 row in set (0.00 sec)

+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Call Procedure from Java:

CallableStatement cstmt = con.prepareCall( "call multi_query()" );  
boolean hasMoreResultSets = cstmt.execute();  
READING_QUERY_RESULTS:  
    while ( hasMoreResultSets ) {  
        Resultset rs = stmt.getResultSet();
        // handle your rs here
    } // while has more rs

Export to CSV using MVC, C# and jQuery

Even if you have resolved your issue, here is another one try to export csv using mvc.

return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName };

Simple way to convert datarow array to datatable

DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}

Argument of type 'X' is not assignable to parameter of type 'X'

For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.

Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@RequestMapping is a class level

@GetMapping is a method-level

With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation

Here is an example:

@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
                            at the class level, specifies the kind of requests 
                            that this controller handles*/  

public class OrderController {

@GetMapping("/current")/*@GetMapping paired with the classlevel
                        @RequestMapping, specifies that when an 
                        HTTP GET request is received for /order, 
                        orderForm() will be called to handle the request..*/

public String orderForm(Model model) {

model.addAttribute("order", new Order());

return "orderForm";
}
}

Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)

Extra reading from a book authored by Craig Walls Extra reading from a book authored by Craig Walls

Stop fixed position at footer

I've made some changes to the second most popular answer as i found this worked better for me. The changes use window.innerHeight as it is more dynamic than adding your own height for the nav (above used + 570). this allows the code to work on mobile, tablet and desktop dynamicly.

$(window).scroll(() => {
            //Distance from top fo document to top of footer
            topOfFooter = $('#footer').position().top;
             // Distance user has scrolled from top + windows inner height
             scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
             // Difference between the two.
             scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter; 
            // If user has scrolled further than footer,
              if (scrollDistanceFromTopOfDoc > topOfFooter) {
                // add margin-bottom so button stays above footer.
                $('#floating-button').css('margin-bottom',  0 + scrollDistanceFromTopOfFooter);
              } else  {
                // remove margin-bottom so button goes back to the bottom of the page
                $('#floating-button').css('margin-bottom', 0);
              }
            });

How to set component default props on React component

use a static defaultProps like:

export default class AddAddressComponent extends Component {
    static defaultProps = {
        provinceList: [],
        cityList: []
    }

render() {
   let {provinceList,cityList} = this.props
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props')
    }
    ...
}

AddAddressComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}

AddAddressComponent.defaultProps = {
  cityList: [],
  provinceList: [],
}

AddAddressComponent.propTypes = {
  userInfo: React.PropTypes.object,
  cityList: PropTypes.array.isRequired,
  provinceList: PropTypes.array.isRequired,
}

Taken from: https://github.com/facebook/react-native/issues/1772

If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.

Trying to merge 2 dataframes but get ValueError

In one of your dataframes the year is a string and the other it is an int64 you can convert it first and then join (e.g. df['year']=df['year'].astype(int) or as RafaelC suggested df.year.astype(int))

Edit: Also note the comment by Anderson Zhu: Just in case you have None or missing values in one of your dataframes, you need to use Int64 instead of int. See the reference here.

C++ Vector of pointers

By dynamically allocating a Movie object with new Movie(), you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as

std::vector<Movie *> movies

But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

div background color, to change onhover

To make the whole div act as a link, set the anchor tag as:

display: block

And set your height of the anchor tag to 100%. Then set a fixed height to your div tag. Then style your anchor tag like usual.

For example:

<html>
<head>
    <title>DIV Link</title>

    <style type="text/css">
    .link-container {
        border: 1px solid;
        width: 50%;
        height: 20px;
    }

    .link-container a {
        display: block;
        background: #c8c8c8;
        height: 100%;
        text-align: center;
    }

    .link-container a:hover {
        background: #f8f8f8;
    }

    </style>

</head>
<body>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

</body> </html>

Good luck!

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For me, the solution was to ensure all projects were building for the same CPU - in my case x86

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

  • The NVARCHAR2 stores variable-length character data. When you create a table with the NVARCHAR2 column, the maximum size is always in character length semantics, which is also the default and only length semantics for the NVARCHAR2 data type.

    The NVARCHAR2data type uses AL16UTF16character set which encodes Unicode data in the UTF-16 encoding. The AL16UTF16 use 2 bytes to store a character. In addition, the maximum byte length of an NVARCHAR2 depends on the configured national character set.

  • VARCHAR2 The maximum size of VARCHAR2 can be in either bytes or characters. Its column only can store characters in the default character set while the NVARCHAR2 can store virtually any characters. A single character may require up to 4 bytes.

By defining the field as:

  • VARCHAR2(10 CHAR) you tell Oracle it can use enough space to store 10 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
  • NVARCHAR2(10) you tell Oracle it can store 10 characters with 2 bytes per character

In Summary:

  • VARCHAR2(10 CHAR) can store maximum of 10 characters and maximum of 40 bytes (depends on the configured national character set).

  • NVARCHAR2(10) can store maximum of 10 characters and maximum of 20 bytes (depends on the configured national character set).

Note: Character set can be UTF-8, UTF-16,....

Please have a look at this tutorial for more detail.

Have a good day!

Check if PHP-page is accessed from an iOS device

Use the user agent from $_SERVER['HTTP_USER_AGENT'], and for simple detection you can use this script:

<?php

//Detect special conditions devices
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
    //browser reported as an iPhone/iPod touch -- do something here
}else if($iPad){
    //browser reported as an iPad -- do something here
}else if($Android){
    //browser reported as an Android device -- do something here
}else if($webOS){
    //browser reported as a webOS device -- do something here
}

?> 

If you want to know more details of the user device I recommended to use one of the following solutions: http://51degrees.mobi or http://deviceatlas.com

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

This error can occur if you project is compiling with JDK 1.6 and you have dependencies compiled with Java 7.

Volley - POST/GET parameters

This helper class manages parameters for GET and POST requests:

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;    

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {
    private int mMethod;
    private String mUrl;
    private Map<String, String> mParams;
    private Listener<JSONObject> mListener;

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mMethod = method;
        this.mUrl = url;
        this.mParams = params;
        this.mListener = reponseListener;
    }

@Override
public String getUrl() {
    if(mMethod == Request.Method.GET) {
        if(mParams != null) {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
            int i = 1;
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                if (i == 1) {
                    stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
                } else {
                    stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
                }
                iterator.remove(); // avoids a ConcurrentModificationException
                i++;
            }
            mUrl = stringBuilder.toString();
        }
    }
    return mUrl;
}

    @Override
    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return mParams;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        mListener.onResponse(response);
    }
}

How can I access "static" class variables within class methods in Python?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Difference between /res and /assets directories

Following are some key points :

  1. Raw files Must have names that are valid Java identifiers , whereas files in Assets Have no location and name restrictions. In other words they can be grouped in whatever directories we wish
  2. Raw files Are easy to refer to from Java as well as from xml (i.e you can refer a file in raw from manifest or other xml file).
  3. Saving asset files here instead of in the assets/ directory only differs in the way that you access them as documented here http://developer.android.com/tools/projects/index.html.
  4. Resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s)
  5. The assets directory is more like a filesystem provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java . like Game data files , Fonts , textures etc.
  6. Unlike Resources, Assets can can be organized into subfolders in the assets directory However, the only thing you can do with an asset is get an input stream. Thus, it does not make much sense to store your strings or bitmaps in assets, but you can store custom-format data such as input correction dictionaries or game maps.
  7. Raw can give you a compile time check by generating your R.java file however If you want to copy your database to private directory you can use Assets which are made for streaming.

Conclusion

  1. Android API includes a very comfortable Resources framework that is also optimized for most typical use cases for various mobile apps. You should master Resources and try to use them wherever possible.
  2. However, if you need more flexibility for your special case, Assets are there to give you a lower level API that allows organizing and processing your resources with a higher degree of freedom.

Get the contents of a table row with a button click

You need to change your code to find the row relative to the button which was clicked. Try this:

$(".use-address").click(function() {
    var id = $(this).closest("tr").find(".nr").text();
    $("#resultas").append(id);
});

Example fiddle

Converting serial port data to TCP/IP in a Linux environment

I had the same problem.

I'm not quite sure about open source applications, but I have tested command line Serial over Ethernet for Linux and... it works for me.

Also thanks to Judge Maygarden for the instructions.

MySQL - UPDATE query with LIMIT

I would suggest a two step query

I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id, substitute with whatever your PK is called.

1 - figure out the primary key number for column 1000.

SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000

2 - update the table.

UPDATE smartmeter_usage.users_reporting SET panel_id = 3 
WHERE panel_id IS NULL AND id >= @id 
ORDER BY id 
LIMIT 1000

Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.

IE8 support for CSS Media Query

IE didn't add media query support until IE9. So with IE8 you're out of luck.

Case statement in MySQL

Yes, something like this:

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

How to read one single line of csv data in Python?

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

Change/Get check state of CheckBox

I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.

function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.

    if(document.getElementById(from).checked==true) 
    //checks status of "from" element. change to whatever validation you prefer.
        {
            document.getElementById(to).checked=true;
             //if validation returns true, checks target checkbox
        }
    else
        {   
            document.getElementById(to).checked=false; 
             //if validation returns true, unchecks target checkbox
        }
}

HTML being something like

<input type="radio" name="bob" onclick="copycheck('from','to');" />

where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to". As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.

Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.

Hope this helps.

Formatting numbers (decimal places, thousands separators, etc) with CSS

The CSS working group has publish a Draft on Content Formatting in 2008. But nothing new right now.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Postgresql SELECT if string contains

You should use 'tag_name' outside of quotes; then its interpreted as a field of the record. Concatenate using '||' with the literal percent signs:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';