Programs & Examples On #Netlink

Netlink is a socket based inter process communication protocol for Linux systems. It is currently the preferred way, as of 2.6, of communicating with user space from the kernel.

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

What jsf component can render a div tag?

Apart from the <h:panelGroup> component (which comes as a bit of a surprise to me), you could use a <f:verbatim> tag with the escape parameter set to false to generate any mark-up you want. For example:

<f:verbatim escape="true">
    <div id="blah"></div>
</f:verbatim>

Bear in mind it's a little less elegant than the panelGroup solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div tag.

Alternatively, all the major UI Frameworks have a div component tag, or you could write your own.

Is there a simple way to convert C++ enum to string?

@hydroo: Without the extra file:

#define SOME_ENUM(DO) \
    DO(Foo) \
    DO(Bar) \
    DO(Baz)

#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
    SOME_ENUM(MAKE_ENUM)
};

#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
    SOME_ENUM(MAKE_STRINGS)
};

C# Macro definitions in Preprocessor

I will create a C# macrocompiler called C#macros.

Progress is here.

Javascript counting number of objects in object

Try Demo Here

var list ={}; var count= Object.keys(list).length;

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

How can I use break or continue within for loop in Twig template?

From docs TWIG docs:

Unlike in PHP, it's not possible to break or continue in a loop.

But still:

You can however filter the sequence during iteration which allows you to skip items.

Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

{% for post in posts|slice(0,10) %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Example 2:

{% for post in posts if post.id < 10 %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

You can even use own TWIG filters for more complexed conditions, like:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Jquery, Clear / Empty all contents of tbody element?

        <table id="table_id" class="table table-hover">
          <thead>
            <tr>
             ...
             ...
            </tr>
          </thead>
        </table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

Can you style html form buttons with css?

Yeah, it's pretty simple:

input[type="submit"]{
  background: #fff;
  border: 1px solid #000;
  text-shadow: 1px 1px 1px #000;
}

I recommend giving it an ID or a class so that you can target it more easily.

flutter remove back button on appbar

I believe the solutions are the following

You actually either:

  • Don't want to display that ugly back button ( :] ), and thus go for : AppBar(...,automaticallyImplyLeading: false,...);

  • Don't want the user to go back - replacing current view - and thus go for: Navigator.pushReplacementNamed(## your routename here ##);

  • Don't want the user to go back - replacing a certain view back in the stack - and thus use: Navigator.pushNamedAndRemoveUntil(## your routename here ##, f(Route<dynamic>)?bool); where f is a function returning truewhen meeting the last view you want to keep in the stack (right before the new one);

  • Don't want the user to go back - EVER - emptying completely the navigator stack with: Navigator.pushNamedAndRemoveUntil(context, ## your routename here ##, (_) => false);

Cheers

How to delete history of last 10 commands in shell?

I use this (I have bash 4):

histrm() {
    local num=${1:- 1}
    builtin history -d $(builtin history | sed -rn '$s/^[^[:digit:]]+([[:digit:]]+)[^[:digit:]].*$/\1/p')
    (( num-- )) && $FUNCNAME $num
    builtin history -w
}

The builtin history parts as well as the last -w is because I have in place a variation of the famous tricks to share history across terminals and this function would break without those parts. They ensure a call to the real bash history builtin (and not to my own wrapper around it), and to write the history to HISTFILE right after the entries were removed.

However this will work as it is with "normal" history configurations.

You should call it with the number of last entries you want to remove, for example:

histrm 10

Will remove the last 10 entries.

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

Retrieving parameters from a URL

Most answers here suggest using parse_qs to parse an URL string. This method always returns the values as a list (not directly as a string) because a parameter can appear multiple times, e.g.:

http://example.com/?foo=bar&foo=baz&bar=baz

Would return:

{'foo': ['bar', 'baz'], 'bar' : ['baz']}

This is a bit inconvenient because in most cases you're dealing with an URL that doesn't have the same parameter multiple times. This function returns the first value by default, and only returns a list if there's more than one element.

from urllib import parse

def parse_urlargs(url):
    query = parse.parse_qs(parse.urlparse(url).query)
    return {k:v[0] if v and len(v) == 1 else v for k,v in query.items()}

For example, http://example.com/?foo=bar&foo=baz&bar=baz would return:

{'foo': ['bar', 'baz'], 'bar': 'baz'}

Execute PHP script in cron job

Automated Tasks: Cron

Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.

Configuring Cron Tasks

In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:

*/10 * * * * /usr/bin/php /opt/test.php

In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.

* is a wildcard, meaning "every time".

Start with finding out your PHP binary by typing in command line:

whereis php

The output should be something like:

php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz

Specify correctly the full path in your command.

Type the following command to enter cronjob:

crontab -e

To see what you got in crontab.

EDIT 1:

To exit from vim editor without saving just click:

Shift+:

And then type q!

3-dimensional array in numpy

Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.

https://opensourceoptions.com/blog/numpy-array-shapes-and-reshaping-arrays/#:~:text=3D%20arrays,order%20layers%2C%20rows%2C%20columns.

Object reference not set to an instance of an object.

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}

How do I check whether an array contains a string in TypeScript?

You can use the some method:

console.log(channelArray.some(x => x === "three")); // true

You can use the find method:

console.log(channelArray.find(x => x === "three")); // three

Or you can use the indexOf method:

console.log(channelArray.indexOf("three")); // 2

jQuery UI Tabs - How to Get Currently Selected Tab Index

You can find it via:

$(yourEl).tabs({
    activate: function(event, ui) {
        console.log(ui.newPanel.index());
    }
});

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you are using npm and browserify:

// es6 imports
import tether from 'tether';
global.Tether = tether;

// require
global.Tether = require('tether');

How to convert JTextField to String and String to JTextField?

The JTextField offers a getText() and a setText() method - those are for getting and setting the content of the text field.

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I was able to overcome this issue with the following Visual Studio 2017 change:

  1. In Team Explorer, go to Settings. Go to Global Settings to configure this option at the global level; go to Repository Settings to configure this option at the repo level.
  2. Set Rebase local branch when pulling to the desired setting (for me it was True), and select Update to save.

See: https://docs.microsoft.com/en-us/vsts/git/concepts/git-config?view=vsts&tabs=visual-studio#rebase-local-branch-when-pulling

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to escape braces (curly brackets) in a format string in .NET

or you can use c# string interpolation like this (feature available in C# 6.0)

var value = "1, 2, 3";
var output = $" foo {{{value}}}";

dropping a global temporary table

  1. Down the apache server by running below in putty cd $ADMIN_SCRIPTS_HOME ./adstpall.sh
  2. Drop the Global temporary tables drop table t;

This will workout..

HTML5 Canvas and Anti-aliasing

It's now 2018, and we finally have cheap ways to do something around it...

Indeed, since the 2d context API now has a filter property, and that this filter property can accept SVGFilters, we can build an SVGFilter that will keep only fully opaque pixels from our drawings, and thus eliminate the default anti-aliasing.

So it won't deactivate antialiasing per se, but provides a cheap way both in term of implementation and of performances to remove all semi-transparent pixels while drawing.

I am not really a specialist of SVGFilters, so there might be a better way of doing it, but for the example, I'll use a <feComponentTransfer> node to grab only fully opaque pixels.

_x000D_
_x000D_
var ctx = canvas.getContext('2d');_x000D_
ctx.fillStyle = '#ABEDBE';_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.font = '14px sans-serif';_x000D_
ctx.textAlign = 'center';_x000D_
_x000D_
// first without filter_x000D_
ctx.fillText('no filter', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
// then with filter_x000D_
ctx.setTransform(1, 0, 0, 1, 120, 0);_x000D_
ctx.filter = 'url(#remove-alpha)';_x000D_
// and do the same ops_x000D_
ctx.fillText('no alpha', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
_x000D_
// to remove the filter_x000D_
ctx.filter = 'none';_x000D_
_x000D_
_x000D_
function drawArc() {_x000D_
  ctx.beginPath();_x000D_
  ctx.arc(60, 80, 50, 0, Math.PI * 2);_x000D_
  ctx.stroke();_x000D_
}_x000D_
_x000D_
function drawTriangle() {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(60, 150);_x000D_
  ctx.lineTo(110, 230);_x000D_
  ctx.lineTo(10, 230);_x000D_
  ctx.closePath();_x000D_
  ctx.stroke();_x000D_
}_x000D_
// unrelated_x000D_
// simply to show a zoomed-in version_x000D_
var zCtx = zoomed.getContext('2d');_x000D_
zCtx.imageSmoothingEnabled = false;_x000D_
canvas.onmousemove = function drawToZoommed(e) {_x000D_
  var x = e.pageX - this.offsetLeft,_x000D_
    y = e.pageY - this.offsetTop,_x000D_
    w = this.width,_x000D_
    h = this.height;_x000D_
    _x000D_
  zCtx.clearRect(0,0,w,h);_x000D_
  zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);_x000D_
}
_x000D_
<svg width="0" height="0" style="position:absolute;z-index:-1;">_x000D_
  <defs>_x000D_
    <filter id="remove-alpha" x="0" y="0" width="100%" height="100%">_x000D_
      <feComponentTransfer>_x000D_
        <feFuncA type="discrete" tableValues="0 1"></feFuncA>_x000D_
      </feComponentTransfer>_x000D_
      </filter>_x000D_
  </defs>_x000D_
</svg>_x000D_
_x000D_
<canvas id="canvas" width="250" height="250" ></canvas>_x000D_
<canvas id="zoomed" width="250" height="250" ></canvas>
_x000D_
_x000D_
_x000D_

And for the ones that don't like to append an <svg> element in their DOM, you can also save it as an external svg file and set the filter property to path/to/svg_file.svg#remove-alpha.

Copy file or directories recursively in Python

shutil.copy and shutil.copy2 are copying files.

shutil.copytree copies a folder with all the files and all subfolders. shutil.copytree is using shutil.copy2 to copy the files.

So the analog to cp -r you are saying is the shutil.copytree because cp -r targets and copies a folder and its files/subfolders like shutil.copytree. Without the -r cp copies files like shutil.copy and shutil.copy2 do.

Checking if a variable is defined?

This is useful if you want to do nothing if it does exist but create it if it doesn't exist.

def get_var
  @var ||= SomeClass.new()
end

This only creates the new instance once. After that it just keeps returning the var.

PHP "php://input" vs $_POST

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3

But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).

The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

How do I assert equality on two classes without an equals method?

Since this question is old, I will suggest another modern approach using JUnit 5.

I don't like this solution because I don't get the full equality picture if an early assert fails.

With JUnit 5, there is a method called Assertions.assertAll() which will allow you to group all assertions in your test together and it will execute each one and output any failed assertions at the end. This means that any assertions that fail first will not stop the execution of latter assertions.

assertAll("Test obj1 with obj2 equality",
    () -> assertEquals(obj1.getFieldA(), obj2.getFieldA()),
    () -> assertEquals(obj1.getFieldB(), obj2.getFieldB()),
    () -> assertEquals(obj1.getFieldC(), obj2.getFieldC()));

How do I restart a service on a remote machine in Windows?

You can use mmc:

  1. Start / Run. Type "mmc".
  2. File / Add/Remove Snap-in... Click "Add..."
  3. Find "Services" and click "Add"
  4. Select "Another computer:" and type the host name / IP address of the remote machine. Click Finish, Close, etc.

At that point you will be able to manage services as if they were on your local machine.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

The second question is easier to answer: you basically can use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy provides the same "forward-facing" tool as Python --- that is, it is Python --- but its innards are different, so tools that interface with those innards won't work.

As for the first question, I imagine it is sort of a Catch-22 with the first: PyPy has been evolving rapidly in an effort to improve speed and enhance interoperability with other code. This has made it more experimental than official.

I think it's possible that if PyPy gets into a stable state, it may start getting more widely used. I also think it would be great for Python to move away from its C underpinnings. But it won't happen for a while. PyPy hasn't yet reached the critical mass where it is almost useful enough on its own to do everything you'd want, which would motivate people to fill in the gaps.

Absolute vs relative URLs

For every system that support relative URI resolution, both relative and absolute URIs do serve the same goal: referencing. And they can be used interchangeably. So you could decide in each case differently. Technically, they provide the same referencing.

To be precise, with each relative URI there already is an absolute URI. And that's the base-URI that relative URI is resolved against. So a relative URI is actually a feature on top of absolute URIs.

And that's also why with relative URIs you can do more as with an absolute URI alone - this is especially important for static websites which otherwise couldn't be as flexible to maintain as compared to absolute URIs.

These positive effects of relative URI resolution can be exploited for dynamic web-application development as well. The inflexibility absolute URIs do introduce are also easier to cope up with, in a dynamic environment, so for some developers that are unsure about URI resolution and how to properly implement and manage it (not that it's always easy) do often opt into using absolute URIs in a dynamic part of a website as they can introduce other dynamic features (e.g. configuration variable containing the URI prefix) so to work around the inflexibility.

So what is the benefit then in using absolute URIs? Technically there ain't, but one I'd say: Relative URIs are more complex because they need to be resolved against the so called absolute base-URI. Even the resolution is strictly define since years, you might run over a client that has a mistake in URI resolution. As absolute URIs do not need any resolution, using absolute URIs have no risk to run into faulty client behaviour with relative URI resolution. So how high is that risk actually? Well, it's very rare. I only know about one Internet browser that had an issue with relative URI resolution. And that was not generally but only in a very (obscure) case.

Next to the HTTP client (browser) it's perhaps more complex for an author of hypertext documents or code as well. Here the absolute URI has the benefit that it is easier to test, as you can just enter it as-is into your browsers address bar. However, if it's not just your one-hour job, it's most often of more benefit to you to actually understand absolute and relative URI handling so that you can actually exploit the benefits of relative linking.

Tool to generate JSON schema from JSON data

You might be looking for this:

http://www.jsonschema.net

It is an online tool that can automatically generate JSON schema from JSON string. And you can edit the schema easily.

Navigation drawer: How do I set the selected item at startup?

There are always problems with Googles "oh so great" support libs. If you want to check an item without downgrading your support libs version, just set checkable before setting checked state.

MenuItem item = drawer.getMenu().findItem(R.id.action_something);
item.setCheckable(true);
item.setChecked(true);

It might also work if you set checkable in the menu xml files

How to implement WiX installer upgrade?

In the newest versions (from the 3.5.1315.0 beta), you can use the MajorUpgrade element instead of using your own.

For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded):

<MajorUpgrade
    AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)"
    AllowSameVersionUpgrades="no"
    />

Error: Cannot access file bin/Debug/... because it is being used by another process

My problem was dotnet got hung up and whenever VS would try to make a new dll, or access an old one, the dotnet process would latch onto the dll and stop visual studio from cloning the dll. Solution is just to end all dotnet tasks in task manager(it will only actually remove the dead one, if you are trying to end one and it won't shut down, that means it's working).

How would I access variables from one class to another?

we can access/pass arguments/variables from one class to another class using object reference.

#Class1
class Test:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.add = 0

    def calc(self):
        self.add = self.a+self.b

#Class 2
class Test2:
    def display(self):
        print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)

How do I add 24 hours to a unix timestamp in php?

Add 24*3600 which is the number of seconds in 24Hours

Adding items to an object through the .push() method

This is really easy: Example

//my object
var sendData = {field1:value1, field2:value2};

//add element
sendData['field3'] = value3;

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How do I install a Python package with a .whl file?

To be able to install wheel files with a simple doubleclick on them you can do one the following:

1) Run two commands in command line under administrator privileges:

assoc .whl=pythonwheel
ftype pythonwheel=cmd /c pip.exe install "%1" ^& pause

2) Alternatively, they can be copied into a wheel.bat file and executed with 'Run as administrator' checkbox in the properties.

PS pip.exe is assumed to be in the PATH.

Update:

(1) Those can be combined in one line:

assoc .whl=pythonwheel& ftype pythonwheel=cmd /c pip.exe install -U "%1" ^& pause

(2) Syntax for .bat files is slightly different:

assoc .whl=pythonwheel& ftype pythonwheel=cmd /c pip.exe install -U "%%1" ^& pause

Also its output can be made more verbose:

@assoc .whl=pythonwheel|| echo Run me with administrator rights! && pause && exit 1
@ftype pythonwheel=cmd /c pip.exe install -U "%%1" ^& pause || echo Installation error && pause && exit 1
@echo Installation successfull & pause

see my blog post for details.

Graphviz's executables are not found (Python 3.4)

Tried many ways and here is what really solved the problem - it worked for both windows 8.1/10 & python 3 .

1 . pip install graphviz

2 . the key action needed is to set the path variable by following steps below:

a. Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit b. add 'C:\Program Files (x86)\Graphviz2.38\bin'

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

255 is used because it's the largest number of characters that can be counted with an 8-bit number. It maximizes the use of the 8-bit count, without frivolously requiring another whole byte to count the characters above 255.

When used this way, VarChar only uses the number of bytes + 1 to store your text, so you might as well set it to 255, unless you want a hard limit (like 50) on the number of characters in the field.

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

How can I compare two ordered lists in python?

The expression a == b should do the job.

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

SonarQube not picking up Unit Test Coverage

The presence of argLine configurations in either of surefire and jacoco plugins stops the jacoco report generation. The argLine should be defined in properties

<properties>
  <argLine>your jvm options here</argLine>
</properties>

__init__() missing 1 required positional argument

You need to pass some data into it. An empty dictionary, for example.

if __name__ == '__main__': DHT('a').showData()

However, in your example a parameter is not even needed. You can declare it by just:

def __init__(self):

Maybe you mean to set it from the data?

class DHT:
    def __init__(self, data):
        self.data['one'] = data['one']
        self.data['two'] = data['two']
        self.data['three'] = data['three']
    def showData(self):
        print(self.data)

if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()

showData will print the data you just entered.

Remove all html tags from php string

Remove all HTML tags from PHP string with content!

Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

echo strip_tags_content($srting);

function strip_tags_content($text) {

    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
    
 }

Output:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

npm notice created a lockfile as package-lock.json. You should commit this file

If this is output from a Dockerfile then you don't want / need to commit it.

However you will want to tag the base image and any other contributing images / applications.

E.g.

FROM node:12.18.1

Difference between Fact table and Dimension table?

  1. The fact table mainly consists of business facts and foreign keys that refer to primary keys in the dimension tables. A dimension table consists mainly of descriptive attributes that are textual fields.
  2. A dimension table contains a surrogate key, natural key, and a set of attributes. On the contrary, a fact table contains a foreign key, measurements, and degenerated dimensions.
  3. Dimension tables provide descriptive or contextual information for the measurement of a fact table. On the other hand, fact tables provide the measurements of an enterprise.
  4. When comparing the size of the two tables, a fact table is bigger than a dimensional table. In a comparison table, more dimensions are presented than the fact tables. In a fact table, less numbers of facts are observed.
  5. The dimension table has to be loaded first. While loading the fact tables, one should have to look at the dimension table. This is because the fact table has measures, facts, and foreign keys that are the primary keys in the dimension table.

Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo

Update and left outer join statements

If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers    
SET city = (SELECT customers.city FROM customers

WHERE customers.customer_name = suppliers.supplier_name)

How to crop an image using PIL?

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)

How to get distinct results in hibernate with joins and row-based limiting (paging)?

You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.

Simply add this to your criteria:

criteria.setProjection(Projections.distinct(Projections.property("id")));

Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check as part of the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness after the sql query has been performed.

Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

How can I align all elements to the left in JPanel?

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

Postgresql column reference "id" is ambiguous

I suppose your p2vg table has also an id field , in that case , postgres cannot find if the id in the SELECT refers to vg or p2vg.

you should use SELECT(vg.id,vg.name) to remove ambiguity

MySQL Workbench Edit Table Data is read only

Guided by Manitoba's post, I found another solution. As a summary, the solutions are:

  1. With a USE command

    USE mydb;
    SELECT * FROM mytable
    
  2. With an explicit schema prefix:

    SELECT * FROM mydb.mytable
    
  3. GUI

    On Object Browser "SCHEMAS" pane, all database icons are initially not highlighted if you have the same issue. So you can right click on the database icon you wanted to be the default, select "Set as default schema".

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

How do I copy a folder from remote to local using scp?

To copy all from Local Location to Remote Location (Upload)

scp -r /path/from/destination username@hostname:/path/to/destination

To copy all from Remote Location to Local Location (Download)

scp -r username@hostname:/path/from/destination /path/to/destination

Custom Port where xxxx is custom port number

 scp -r -P xxxx username@hostname:/path/from/destination /path/to/destination

Copy on current directory from Remote to Local

scp -r username@hostname:/path/from/file .

Help:

  1. -r Recursively copy all directories and files
  2. Always use full location from /, Get full location by pwd
  3. scp will replace all existing files
  4. hostname will be hostname or IP address
  5. if custom port is needed (besides port 22) use -P portnumber
  6. . (dot) - it means current working directory, So download/copy from server and paste here only.

Note: Sometimes the custom port will not work due to the port not being allowed in the firewall, so make sure that custom port is allowed in the firewall for incoming and outgoing connection

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

SELECT * FROM in MySQLi

Is this statement a thing of the past?

Yes. Don't use SELECT *; it's a maintenance nightmare. There are tons of other threads on SO about why this construct is bad, and how avoiding it will help you write better queries.

See also:

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

How can I compare strings in C using a `switch` statement?

My preferred method for doing this is via a hash function (borrowed from here). This allows you to utilize the efficiency of a switch statement even when working with char *'s:

#include "stdio.h"

#define LS 5863588
#define CD 5863276
#define MKDIR 210720772860
#define PWD 193502992

const unsigned long hash(const char *str) {
    unsigned long hash = 5381;  
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + c;
    return hash;
}

int main(int argc, char *argv[]) {
    char *p_command = argv[1];
    switch(hash(p_command)) {
    case LS:
        printf("Running ls...\n");
        break;
    case CD:
        printf("Running cd...\n");
        break;
    case MKDIR:
        printf("Running mkdir...\n");
        break;
    case PWD:
        printf("Running pwd...\n");
        break;
    default:
        printf("[ERROR] '%s' is not a valid command.\n", p_command);
    }
}

Of course, this approach requires that the hash values for all possible accepted char *'s are calculated in advance. I don't think this is too much of an issue; however, since the switch statement operates on fixed values regardless. A simple program can be made to pass char *'s through the hash function and output their results. These results can then be defined via macros as I have done above.

Get file version in PowerShell

Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.

(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

You can specify maven source/target version by adding these properties to your pom.xml file

<properties>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
</properties>

Entity Framework Core add unique constraint code-first

None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

In the instance below I want to ensure the OutletRef field is unique:

public class ApplicationDbContext : IdentityDbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Outlet>()
                .HasIndex(o => new { o.OutletRef });
        }
    }

This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

Updating version numbers of modules in a multi-module Maven project

Use versions:set from the versions-maven plugin:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT

It will adjust all pom versions, parent versions and dependency versions in a multi-module project.

If you made a mistake, do

mvn versions:revert

afterwards, or

mvn versions:commit

if you're happy with the results.


Note: this solution assumes that all modules use the aggregate pom as parent pom also, a scenario that was considered standard at the time of this answer. If that is not the case, go for Garret Wilson's answer.

How to start a background process in Python?

I found this here:

On windows (win xp), the parent process will not finish until the longtask.py has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.

The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

Solving "adb server version doesn't match this client" error

This issue for me was caused by having apowermirror running at the same time, from what I can tell any software that could use a different version of adb could cause these issues as others mention in this thread this can include Genymotion or from other threads unreal studio was the problem.

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Wrap long lines in Python

You can use the fact that Python concatenates string literals which appear adjacent to each other:

>>> def fun():
...     print '{0} Here is a really long ' \
...           'sentence with {1}'.format(3, 5)

How to extract a value from a string using regex and a shell?

you can use the shell(bash for example)

$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45

target="_blank" vs. target="_new"

The target attribute of a link forces the browser to open the destination page in a new browser window. Using _blank as a target value will spawn a new window every time while using _new will only spawn one new window and every link clicked with a target value of _new will replace the page loaded in the previously spawned window

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

How can I verify a Google authentication API access token?

you can verify a Google authentication access token by using this endpoint:

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>

This is Google V3 OAuth AccessToken validating endpoint, you can refer from google document below: (In OAUTH 2.0 ENDPOINTS Tab)

https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token

When to use reinterpret_cast?

First you have some data in a specific type like int here:

int x = 0x7fffffff://==nan in binary representation

Then you want to access the same variable as an other type like float: You can decide between

float y = reinterpret_cast<float&>(x);

//this could only be used in cpp, looks like a function with template-parameters

or

float y = *(float*)&(x);

//this could be used in c and cpp

BRIEF: it means that the same memory is used as a different type. So you could convert binary representations of floats as int type like above to floats. 0x80000000 is -0 for example (the mantissa and exponent are null but the sign, the msb, is one. This also works for doubles and long doubles.

OPTIMIZE: I think reinterpret_cast would be optimized in many compilers, while the c-casting is made by pointerarithmetic (the value must be copied to the memory, cause pointers couldn't point to cpu- registers).

NOTE: In both cases you should save the casted value in a variable before cast! This macro could help:

#define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })

Converting Integer to Long

If you don't know the exact class of your number (Integer, Long, Double, whatever), you can cast to Number and get your long value from it:

Object num = new Integer(6);
Long longValue = ((Number) num).longValue();

How to Decrease Image Brightness in CSS

If you have a background-image, you can do this : Set a rgba() gradient on the background-image.

_x000D_
_x000D_
.img_container {_x000D_
  float: left;_x000D_
  width: 300px;_x000D_
  height: 300px;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border : 1px solid #fff;_x000D_
}_x000D_
_x000D_
.image_original {_x000D_
  background: url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.image_brighness {_x000D_
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), /* the gradient on top, adjust color and opacity to your taste */_x000D_
  url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.img_container p {_x000D_
  color: #fff;_x000D_
  font-size: 28px;_x000D_
}
_x000D_
<div class="img_container image_original">_x000D_
  <p>normal</p>_x000D_
</div>_x000D_
<div class="img_container image_brighness ">_x000D_
  <p>less brightness</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Keyboard shortcut to comment lines in Sublime Text 2

By default on Linux/Windows for an English keyboard the shortcut is Ctrl+Shift+/ to toggle a block comment, and Ctrl+/ to toggle a line comment.

If you go into Preferences->Key Bindings - Default, you can find all the shortcuts, below are the lines for commenting.

{ "keys": ["ctrl+/"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+/"], "command": "toggle_comment", "args": { "block": true } },

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I resolve this problem with following function. I use Visual Studio 2019.

FILE* __cdecl __iob_func(void)
{
    FILE _iob[] = { *stdin, *stdout, *stderr };
    return _iob;
}

because stdin Macro defined function call, "*stdin" expression is cannot used global array initializer. But local array initialier is possible. sorry, I am poor at english.

datetime dtypes in pandas read_csv

You might try passing actual types instead of strings.

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

But it's going to be really hard to diagnose this without any of your data to tinker with.

And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:

pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

Python not working in the command line of git bash

I know this is an old post, but I just came across this problem on Windows 10 running Python 3.8.5 and Git 2.28.0.windows.1

Somehow I had several different 2.7x versions of Python installed as well. I removed every version of Python (3x and 2x), downloaded the official installer here, installed 3.8.5 fresh (just used the defaults) which installed Python 3.8.5 at this location:

C:\Users\(my username)\AppData\Local\Programs\Python\Python38

Then to get the command python to work in my git bash shell, I had to manually add the path to Python38 to my path variable following the instructions listed here. This is important to note because on the python installer at the bottom of the first modal that comes up it asks if you want to add the python path to your PATH environment variable. I clicked the checkbox next to this but it didn't actually add the path, hence the need to manually add the path to my PATH environment variable.

Now using my gitbash shell I can browse to a directory with a python script in it and just type python theScriptName.py and it runs no problem.

I wanted to post this because this is all I had to do to get my gitbash shell to allow me to run python scripts. I think there might have been some updates so I didn't need to do any of the other solutions listed here. At any rate, this is another thing to try if you are having issues running python scripts in your gitbash shell on a Windows 10 machine.

Enjoy.

What is the syntax meaning of RAISERROR()

The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block. I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block. I demonstrate this in the gif as well.

BEGIN TRY
    /* RAISERROR with severity 11-19 will cause execution
     |  to jump to the CATCH block.
    */
    RAISERROR ('Error raised in TRY block.', -- Message text.
               5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
               1 -- State.
               );
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage  NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState    INT;

    SELECT 
        @ErrorMessage  = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState    = ERROR_STATE();

    /* Use RAISERROR inside the CATCH block to return error
     | information about the original error that caused
     | execution to jump to the CATCH block
    */
    RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
               @ErrorSeverity,                           /* Severity     */
               @ErrorState                               /* State        */
               );
END CATCH;

RAISERROR Demo Gif

Mocking static methods with Mockito

There is an easy solution by using java FunctionalInterface and then add that interface as dependency for the class you are trying to unit test.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

You may get more success if you do a "search" for the runtime env from the preferences screen instead of hitting "add" - see this demo on youtube. http://www.youtube.com/watch?v=EOkN5IPoJVs&playnext_from=TL&videos=rVnITzSU2Z8 - When you hit search, you are prompted to point to the tomcat directory and then it SHOULD add it as a server runtime environment. Unfortunately for me, that is not the case (I get "no new server runtime environments were found") But you might have more success.

Volatile boolean vs AtomicBoolean

If there are multiple threads accessing class level variable then each thread can keep copy of that variable in its threadlocal cache.

Making the variable volatile will prevent threads from keeping the copy of variable in threadlocal cache.

Atomic variables are different and they allow atomic modification of their values.

Asynchronously wait for Task<T> to complete with timeout

Use a Timer to handle the message and automatic cancellation. When the Task completes, call Dispose on the timers so that they will never fire. Here is an example; change taskDelay to 500, 1500, or 2500 to see the different cases:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        private static Task CreateTaskWithTimeout(
            int xDelay, int yDelay, int taskDelay)
        {
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            var task = Task.Factory.StartNew(() =>
            {
                // Do some work, but fail if cancellation was requested
                token.WaitHandle.WaitOne(taskDelay);
                token.ThrowIfCancellationRequested();
                Console.WriteLine("Task complete");
            });
            var messageTimer = new Timer(state =>
            {
                // Display message at first timeout
                Console.WriteLine("X milliseconds elapsed");
            }, null, xDelay, -1);
            var cancelTimer = new Timer(state =>
            {
                // Display message and cancel task at second timeout
                Console.WriteLine("Y milliseconds elapsed");
                cts.Cancel();
            }
                , null, yDelay, -1);
            task.ContinueWith(t =>
            {
                // Dispose the timers when the task completes
                // This will prevent the message from being displayed
                // if the task completes before the timeout
                messageTimer.Dispose();
                cancelTimer.Dispose();
            });
            return task;
        }

        static void Main(string[] args)
        {
            var task = CreateTaskWithTimeout(1000, 2000, 2500);
            // The task has been started and will display a message after
            // one timeout and then cancel itself after the second
            // You can add continuations to the task
            // or wait for the result as needed
            try
            {
                task.Wait();
                Console.WriteLine("Done waiting for task");
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Error waiting for task:");
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine(e);
                }
            }
        }
    }
}

Also, the Async CTP provides a TaskEx.Delay method that will wrap the timers in tasks for you. This can give you more control to do things like set the TaskScheduler for the continuation when the Timer fires.

private static Task CreateTaskWithTimeout(
    int xDelay, int yDelay, int taskDelay)
{
    var cts = new CancellationTokenSource();
    var token = cts.Token;
    var task = Task.Factory.StartNew(() =>
    {
        // Do some work, but fail if cancellation was requested
        token.WaitHandle.WaitOne(taskDelay);
        token.ThrowIfCancellationRequested();
        Console.WriteLine("Task complete");
    });

    var timerCts = new CancellationTokenSource();

    var messageTask = TaskEx.Delay(xDelay, timerCts.Token);
    messageTask.ContinueWith(t =>
    {
        // Display message at first timeout
        Console.WriteLine("X milliseconds elapsed");
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    var cancelTask = TaskEx.Delay(yDelay, timerCts.Token);
    cancelTask.ContinueWith(t =>
    {
        // Display message and cancel task at second timeout
        Console.WriteLine("Y milliseconds elapsed");
        cts.Cancel();
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    task.ContinueWith(t =>
    {
        timerCts.Cancel();
    });

    return task;
}

How to trigger the window resize event in JavaScript?

Combining pomber's and avetisk's answers to cover all browsers and not causing warnings:

if (typeof(Event) === 'function') {
  // modern browsers
  window.dispatchEvent(new Event('resize'));
} else {
  // for IE and other old browsers
  // causes deprecation warning on modern browsers
  var evt = window.document.createEvent('UIEvents'); 
  evt.initUIEvent('resize', true, false, window, 0); 
  window.dispatchEvent(evt);
}

No Android SDK found - Android Studio

Download android sdk through this sdk manager https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip (note this link is for mac) open android studio, click next, open where it ask to add path where u downloaded sdk..... add it... click next, it will downloaad updates..... and it done

Boolean Field in Oracle

Either 1/0 or Y/N with a check constraint on it. ether way is fine. I personally prefer 1/0 as I do alot of work in perl, and it makes it really easy to do perl Boolean operations on database fields.

If you want a really in depth discussion of this question with one of Oracles head honchos, check out what Tom Kyte has to say about this Here

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

What's the best way to limit text length of EditText in Android

Due to goto10's observation, I put together the following code to protected against loosing other filters with setting the max length:

/**
 * This sets the maximum length in characters of an EditText view. Since the
 * max length must be done with a filter, this method gets the current
 * filters. If there is already a length filter in the view, it will replace
 * it, otherwise, it will add the max length filter preserving the other
 * 
 * @param view
 * @param length
 */
public static void setMaxLength(EditText view, int length) {
    InputFilter curFilters[];
    InputFilter.LengthFilter lengthFilter;
    int idx;

    lengthFilter = new InputFilter.LengthFilter(length);

    curFilters = view.getFilters();
    if (curFilters != null) {
        for (idx = 0; idx < curFilters.length; idx++) {
            if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                curFilters[idx] = lengthFilter;
                return;
            }
        }

        // since the length filter was not part of the list, but
        // there are filters, then add the length filter
        InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
        System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
        newFilters[curFilters.length] = lengthFilter;
        view.setFilters(newFilters);
    } else {
        view.setFilters(new InputFilter[] { lengthFilter });
    }
}

How to get element value in jQuery

Most probably, you want something like this:

$("#list li").click(function() {
        var selected = $(this).html();
        alert(selected);
});

Error handling with PHPMailer

Please note!!! You must use the following format when instantiating PHPMailer!

$mail = new PHPMailer(true);

If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.

how to increase sqlplus column output length?

On Windows you may try this:

  • right-click in the sqlplus window
  • select properties ->layout
  • increase screen buffer size width to 1000

How to convert List<Integer> to int[] in Java?

I would recommend you to use List<?> skeletal implementation from the java collections API, it appears to be quite helpful in this particular case:

package mypackage;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {

//Helper method to convert int arrays into Lists
static List<Integer> intArrayAsList(final int[] a) {
    if(a == null)
        throw new NullPointerException();
    return new AbstractList<Integer>() {

        @Override
        public Integer get(int i) {
            return a[i];//autoboxing
        }
        @Override
        public Integer set(int i, Integer val) {
            final int old = a[i];
            a[i] = val;//auto-unboxing
            return old;//autoboxing
        }
        @Override
        public int size() {
            return a.length;
        }
    };
}

public static void main(final String[] args) {
    int[] a = {1, 2, 3, 4, 5};
    Collections.reverse(intArrayAsList(a));
    System.out.println(Arrays.toString(a));
}
}

Beware of boxing/unboxing drawbacks

Why is datetime.strptime not working in this simple example?

Because datetime is the module. The class is datetime.datetime.

import datetime
dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")

What is the difference between an int and an Integer in Java and C#?

Java:

int, double, long, byte, float, double, short, boolean, char - primitives. Used for hold the basic data types supported by the language. the primitive types are not part of the object hierarchy, and they do not inherit Object. Thet can'be pass by reference to a method.

Double, Float, Long, Integer, Short, Byte, Character, and Boolean, are type Wrappers, packaged in java.lang. All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. Using objects can add an overhead to even the simplest of calculations.

Beginning with JDK 5, Java has included two very helpful features: autoboxing and autounboxing. Autoboxing/unboxing greatly simplifies and streamlines code that must convert primitive types into objects, and vice versa.

Example of constructors:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

Example of boxing/unboxing:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

Example of autoboxing/autounboxing:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

P.S. Herbert Schildt's book was taken as a reference.

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

How to connect to Oracle 11g database remotely

Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.

Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.

Min/Max of dates in an array?

The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :

function getMax(dateArray, filler) {
      filler= filler?filler:"";
      if (!dateArray.length) {
        return filler;
      }
      var max = "";
      dateArray.forEach(function(date) {
        if (date) {
          var d = new Date(date);
          if (max && d.valueOf()>max.valueOf()) {
            max = d;
          } else if (!max) {
            max = d;
          }
        }
      });
      return max;
    };
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));

function getMin(dateArray, filler) {
 filler = filler ? filler : "";
  if (!dateArray.length) {
    return filler;
  }
  var min = "";
  dateArray.forEach(function(date) {
    if (date) {
      var d = new Date(date);
      if (min && d.valueOf() < min.valueOf()) {
        min = d;
      } else if (!min) {
        min = d;
      }
    }
  });
  return min;
}

console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));

I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen

Capturing browser logs with Selenium WebDriver using Java

A less elegant solution is taking the log 'manually' from the user data dir:

  1. Set the user data dir to a fixed place:

    options = new ChromeOptions();
    capabilities = DesiredCapabilities.chrome();
    options.addArguments("user-data-dir=/your_path/");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    
  2. Get the text from the log file chrome_debug.log located in the path you've entered above.

I use this method since RemoteWebDriver had problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.

When to use Task.Delay, when to use Thread.Sleep?

My opinion,

Task.Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep() doesn't return anything ). You can check if this task is completed(use Task.IsCompleted property) later after another time-consuming process.

Thread.Sleep() doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.

As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep() in production code. I couldn't find any use case for it. Maybe that's because I mostly do web application development.

What is the difference between "is None" and "== None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

Make div stay at bottom of page's content all the time even when there are scrollbars

I realise it says not to use this for 'responding to other answers' but unfortunately I don't have enough rep to add a comment onto the appropriate answer (!) but ...

If you are having problems in asp.net with the answer from 'My Head Hurts' - you need to add 'height : 100%' to the main generated FORM tag as well as HTML and BODY tags in order for this to work.

Set 4 Space Indent in Emacs in Text Mode

Have you tried

(setq  tab-width  4)

Create a circular button in BS3

(Not cross-browser tested), but this is my answer:

.btn-circle {
  width: 40px;
  height: 40px;
  line-height: 40px; /* adjust line height to align vertically*/
  padding:0;
  border-radius: 50%;
}
  • vertical center via the line-height property
  • padding becomes useless and must be reset
  • border-radius independant of the button size

Ordering by specific field value first

This works for me using Postgres 9+:

SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

How do I simulate placeholder functionality on input date field?

use this input attribute events

onfocus="(this.type='date')" onblur="(this.type='text')"

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<div class="container mt-3">_x000D_
  <label for="date">Date : </label>_x000D_
  <input placeholder="Your Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I've experienced similar problems with my ASP.NET Core projects. What happens is that the .config file in the bin/debug-folder is generated with this:

  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="6.0.0.0" newVersion="9.0.0.0" />
    <bindingRedirect oldVersion="10.0.0.0" newVersion="9.0.0.0" />
  </dependentAssembly>

If I manually change the second bindingRedirect to this it works:

<bindingRedirect oldVersion="9.0.0.0" newVersion="10.0.0.0" />

Not sure why this happens.

I'm using Visual Studio 2015 with .Net Core SDK 1.0.0-preview2-1-003177.

Is there an opposite to display:none?

opposite of 'none' is 'flex' while working with react native.

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

Get value from hidden field using jQuery

var x = $('#h_v').val();
alert(x);

Environment variable substitution in sed

?. bad way: change delimiter

sed 's/xxx/'"$PWD"'/'
sed 's:xxx:'"$PWD"':'
sed 's@xxx@'"$PWD"'@'

maybe those not the final answer,

you can not known what character will occur in $PWD, / : OR @.

the good way is replace(escape) the special character in $PWD.

?. good way: escape delimiter

for example: try to replace URL as $url (has : / in content)

x.com:80/aa/bb/aa.js

in string $tmp

<a href="URL">URL</a>

A. use / as delimiter

escape / as \/ in var (before use in sed expression)

echo ${url//\//\\/}
x.com:80\/aa\/bb\/aa.js   #escape fine

echo ${url//\//\/}
x.com:80/aa/bb/aa.js      #escape not success

echo "${url//\//\/}"
x.com:80\/aa\/bb\/aa.js   #escape fine, notice `"`

echo $tmp | sed "s/URL/${url//\//\\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>

echo $tmp | sed "s/URL/${url//\//\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>

OR

B. use : as delimiter (more readable than /)

escape : as \: in var (before use in sed expression)

echo ${url//:/\:}
x.com:80/aa/bb/aa.js     #escape not success

echo "${url//:/\:}"
x.com\:80/aa/bb/aa.js    #escape fine, notice `"`

echo $tmp | sed "s:URL:${url//:/\:}:g"
<a href="x.com:80/aa/bb/aa.js">x.com:80/aa/bb/aa.js</a>

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

What is the best way to create a string array in python?

If you want to take input from user here is the code

If each string is given in new line:

strs = [input() for i in range(size)]

If the strings are separated by spaces:

strs = list(input().split())

Validate fields after user has left a field

Regarding @lambinator's solution... I was getting the following error in angular.js 1.2.4:

Error: [$rootScope:inprog] $digest already in progress

I'm not sure if I did something wrong or if this is a change in Angular, but removing the scope.$apply statements resolved the problem and the classes/states are still getting updated.

If you are also seeing this error, give the following a try:

var blurFocusDirective = function () {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function (scope, elm, attr, ctrl) {
      if (!ctrl) {
        return;
      }
      elm.on('focus', function () {
        elm.addClass('has-focus');
        ctrl.$hasFocus = true;
      });

      elm.on('blur', function () {
        elm.removeClass('has-focus');
        elm.addClass('has-visited');
        ctrl.$hasFocus = false;
        ctrl.$hasVisited = true;
      });

      elm.closest('form').on('submit', function () {
        elm.addClass('has-visited');

        scope.$apply(function () {
          ctrl.hasFocus = false;
          ctrl.hasVisited = true;
        });
      });
    }
  };
};
app.directive('input', blurFocusDirective);
app.directive('select', blurFocusDirective);

How do I parse JSON into an int?

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :

int id = jsonObj.getInt("id");

What's a simple way to get a text input popup dialog box on an iPhone

Swift 3:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
     textField.placeholder = "Enter text:"
})

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

Auto-indent in Notepad++

First download plugin manager this link then unzip the zip folder and copy this inside your program/ notepad++ folder . then restart your notepad++. then you see plugin manager inside plugin menu . then click plugin manager then click show plugin manager . It shows all your plugin list . from the list in bottom find XML tools , checked it and install it. then restart your notepad++. After open a document then plugins/xml tools/pretty plain(indent text) then enjoy.

jQuery Validation plugin: validate check box

There is the easy way

HTML:

<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]"  />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>

JQUERY:

$("#submit").on("click",function(){
    if (($("input[name*='test']:checked").length)<=0) {
        alert("You must check at least 1 box");
    }
    return true;
});

For this you not need any plugin. Enjoy;)

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Eloquent ->first() if ->exists()

get returns Collection and is rather supposed to fetch multiple rows.

count is a generic way of checking the result:

$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user

// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException

// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users

How to change an input button image using CSS?

You can use the <button> tag. For a submit, simply add type="submit". Then use a background image when you want the button to appear as a graphic.

Like so:

<button type="submit" style="border: 0; background: transparent">
    <img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>

More info: http://htmldog.com/reference/htmltags/button/

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

How to yum install Node.JS on Amazon Linux

I just came across this. I tried a few of the more popular answers, but in the end, what worked for me was Amazon's quick setup guide.

Tutorial: Setting Up Node.js on an Amazon EC2 Instance

The gist of the tutorial is:

  1. Make sure you are ssh'd onto the instance.
  2. Grab nvm: curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
  3. Active . ~/.nvm/nvm.sh
  4. Install node using nvm nvm install 4.4.5 (NOTE: You can choose a different version. Check out the remote versions first by running $ nvm ls-remote)
  5. Finally, test that you have installed node Node correctly by running $ node -e "console.log('Running Node.js' + process.version)"

Hopefully this helps the next person.

Remove the newline character in a list read from a file

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

What is the difference between window, screen, and document in Javascript?

the window contains everything, so you can call window.screen and window.document to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/

You can also see the contents of the object in firebug/dev tools like this:

console.dir(window);
console.dir(document);
console.dir(screen);

window is the root of everything, screen just has screen dimensions, and document is top DOM object. so you can think of it as window being like a super-document...

How to preSelect an html dropdown list with php?

I suppose that you are using an array to create your select form input. In that case, use an array:

<?php
    $selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
    $fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
 ?>
  <select name=‘yesnofine'>
 <?php foreach ($fields as $k => $v): ?>
  <option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
 <?php endforeach; ?>
 </select>

If not, you may just unroll the above loop, and still use an array.

 <option value="1" <?php @print($selected[$k]);?>>Yes</options>
 <option value="2" <?php @print($selected[$k]);?>>No</options>
 <option value="3" <?php @print($selected[$k]);?>>Fine</options>

Notes that I don't know:

  • how you are naming your input, so I made up a name for it.
  • which way you are handling your form input on server side, I used $_REQUEST,

You will have to adapt the code to match requirements of the framework you are using, if any.

Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.

How To Set Text In An EditText

If you want to set text at design time in xml file just simple android:text="username" add this property.

<EditText
    android:id="@+id/edtUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="username"/>

If you want to set text programmatically in Java

EditText edtUsername = findViewById(R.id.edtUsername);
edtUsername.setText("username");

and in kotlin same like java using getter/setter

edtUsername.setText("username")

But if you want to use .text from principle then

edtUsername.text = Editable.Factory.getInstance().newEditable("username")

because of EditText.text requires an editable at firstplace not String

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

Git Bash won't run my python files?

Tried multiple of these, I switched to Cygwin instead which fixed python and some other problems I was having on Windows:

https://www.cygwin.com/

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Woocommerce, get current product id

your can query woocommerce programatically you can even add a product to your shopping cart. I'm sure you can figure out how to interact with woocommerce cart once you read the code. how to interact with woocommerce cart programatically

====================================

<?php

add_action('wp_loaded', 'add_product_to_cart');
function add_product_to_cart()
{
    global $wpdb;

    if (!is_admin()) {


        $product_id = wc_get_product_id_by_sku('L3-670115');

        $found = false;

        if (is_user_logged_in()) {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->get_id() == $product_id)
                        WC()->cart->remove_cart_item($cart_item_key);
                }
            }
        } else {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->id == $product_id)
                        $found = true;
                }
                // if product not found, add it
                if (!$found)
                    WC()->cart->add_to_cart($product_id);
            } else {
                // if no products in cart, add it
                WC()->cart->add_to_cart($product_id);
            }
        }
    }
}

How to make return key on iPhone make keyboard disappear?

Set the Delegate of the UITextField to your ViewController, add a referencing outlet between the File's Owner and the UITextField, then implement this method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{
   if (textField == yourTextField) 
   {
      [textField resignFirstResponder]; 
   }
   return NO;
}

Recommended way of making React component/div draggable

I've updated polkovnikov.ph solution to React 16 / ES6 with enhancements like touch handling and snapping to a grid which is what I need for a game. Snapping to a grid alleviates the performance issues.

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

class Draggable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            relX: 0,
            relY: 0,
            x: props.x,
            y: props.y
        };
        this.gridX = props.gridX || 1;
        this.gridY = props.gridY || 1;
        this.onMouseDown = this.onMouseDown.bind(this);
        this.onMouseMove = this.onMouseMove.bind(this);
        this.onMouseUp = this.onMouseUp.bind(this);
        this.onTouchStart = this.onTouchStart.bind(this);
        this.onTouchMove = this.onTouchMove.bind(this);
        this.onTouchEnd = this.onTouchEnd.bind(this);
    }

    static propTypes = {
        onMove: PropTypes.func,
        onStop: PropTypes.func,
        x: PropTypes.number.isRequired,
        y: PropTypes.number.isRequired,
        gridX: PropTypes.number,
        gridY: PropTypes.number
    }; 

    onStart(e) {
        const ref = ReactDOM.findDOMNode(this.handle);
        const body = document.body;
        const box = ref.getBoundingClientRect();
        this.setState({
            relX: e.pageX - (box.left + body.scrollLeft - body.clientLeft),
            relY: e.pageY - (box.top + body.scrollTop - body.clientTop)
        });
    }

    onMove(e) {
        const x = Math.trunc((e.pageX - this.state.relX) / this.gridX) * this.gridX;
        const y = Math.trunc((e.pageY - this.state.relY) / this.gridY) * this.gridY;
        if (x !== this.state.x || y !== this.state.y) {
            this.setState({
                x,
                y
            });
            this.props.onMove && this.props.onMove(this.state.x, this.state.y);
        }        
    }

    onMouseDown(e) {
        if (e.button !== 0) return;
        this.onStart(e);
        document.addEventListener('mousemove', this.onMouseMove);
        document.addEventListener('mouseup', this.onMouseUp);
        e.preventDefault();
    }

    onMouseUp(e) {
        document.removeEventListener('mousemove', this.onMouseMove);
        document.removeEventListener('mouseup', this.onMouseUp);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);
        e.preventDefault();
    }

    onMouseMove(e) {
        this.onMove(e);
        e.preventDefault();
    }

    onTouchStart(e) {
        this.onStart(e.touches[0]);
        document.addEventListener('touchmove', this.onTouchMove, {passive: false});
        document.addEventListener('touchend', this.onTouchEnd, {passive: false});
        e.preventDefault();
    }

    onTouchMove(e) {
        this.onMove(e.touches[0]);
        e.preventDefault();
    }

    onTouchEnd(e) {
        document.removeEventListener('touchmove', this.onTouchMove);
        document.removeEventListener('touchend', this.onTouchEnd);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);
        e.preventDefault();
    }

    render() {
        return <div
            onMouseDown={this.onMouseDown}
            onTouchStart={this.onTouchStart}
            style={{
                position: 'absolute',
                left: this.state.x,
                top: this.state.y,
                touchAction: 'none'
            }}
            ref={(div) => { this.handle = div; }}
        >
            {this.props.children}
        </div>;
    }
}

export default Draggable;

How can I do string interpolation in JavaScript?

Douglas Crockford's Remedial JavaScript includes a String.prototype.supplant function. It is short, familiar, and easy to use:

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));

If you don't want to change String's prototype, you can always adapt it to be standalone, or place it into some other namespace, or whatever.

PDO mysql: How to know if insert was successful

If an update query executes with values that match the current database record then $stmt->rowCount() will return 0 for no rows were affected. If you have an if( rowCount() == 1 ) to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.

$stmt->execute();
if( $stmt ) return "success";

This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

There seem to be a lot of issues related to the same error. For me it was the applications which I've installed from another iMac whose files where not present on my MacBook so Xcode was not able to find the files making the debugger to wait forever!

Solution: Deleting all the application which I've installed from the iMac helped me solve the problem.

How do I remove lines between ListViews on Android?

There are different ways to achieve this, but I'm not sure which one is the best (I don't even know is there is a best way). I know at least two different ways to do this in a ListView:

1. Set divider to null:

1.1. Programmatically

yourListView.setDivider(null);

1.2. XML

This goes inside your ListView element.

android:divider="@null"

2. Set divider to transparent and set its height to 0 to avoid adding space between listview elements:

2.1. Programmatically:

yourListView.setDivider(new ColorDrawable(android.R.color.transparent));
yourListView.setDividerHeight(0);

2.2. XML

android:divider="@android:color/transparent"
android:dividerHeight="0dp"

Using HTML and Local Images Within UIWebView

In Swift 3:

webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)

This worked for me even when the image was inside of a folder without any modifications.

How to get the Android device's primary e-mail address

Android locked down GET_ACCOUNTS recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.

AndroidManifest.xml

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

MainActivity.java

package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;

public class MainActivity extends AppCompatActivity {

    final static int requestcode = 4; //arbitrary constant less than 2^16

    private static String getEmailId(Context context) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];
        } else {
            return "length is zero";
        }
        return account.name;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case requestcode:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    String emailAddr = getEmailId(getApplicationContext());
                    ShowMessage(emailAddr);

                } else {
                    ShowMessage("Permission Denied");
                }
        }
    }

    public void ShowMessage(String email)
    {
        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(email);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context context = getApplicationContext();

        if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
                != PackageManager.PERMISSION_GRANTED )
        {
            ActivityCompat.requestPermissions( this, new String[]
                            {  android.Manifest.permission.GET_ACCOUNTS  },requestcode );
        }
        else
        {
            String possibleEmail = getEmailId(getApplicationContext());
            ShowMessage(possibleEmail);
        }
    }
}

QString to char* conversion

EDITED

this way also works

QString str ("Something");

char* ch = str.toStdString().C_str();

Typescript: How to extend two classes?

Unfortunately typescript does not support multiple inheritance. Therefore there is no completely trivial answer, you will probably have to restructure your program

Here are a few suggestions:

  • If this additional class contains behaviour that many of your subclasses share, it makes sense to insert it into the class hierarchy, somewhere at the top. Maybe you could derive the common superclass of Sprite, Texture, Layer, ... from this class ? This would be a good choice, if you can find a good spot in the type hirarchy. But I would not recommend to just insert this class at a random point. Inheritance expresses an "Is a - relationship" e.g. a dog is an animal, a texture is an instance of this class. You would have to ask yourself, if this really models the relationship between the objects in your code. A logical inheritance tree is very valuable

  • If the additional class does not fit logically into the type hierarchy, you could use aggregation. That means that you add an instance variable of the type of this class to a common superclass of Sprite, Texture, Layer, ... Then you can access the variable with its getter/setter in all subclasses. This models a "Has a - relationship".

  • You could also convert your class into an interface. Then you could extend the interface with all your classes but would have to implement the methods correctly in each class. This means some code redundancy but in this case not much.

You have to decide for yourself which approach you like best. Personally I would recommend to convert the class to an interface.

One tip: Typescript offers properties, which are syntactic sugar for getters and setters. You might want to take a look at this: http://blogs.microsoft.co.il/gilf/2013/01/22/creating-properties-in-typescript/

how to implement Pagination in reactJs

A ReactJS dumb component to render pagination. You can also use this Library:

https://www.npmjs.com/package/react-js-pagination

Some Examples are Here:

http://vayser.github.io/react-js-pagination/

OR

You can also Use this https://codepen.io/PiotrBerebecki/pen/pEYPbY

How to get whole and decimal part of a number?

$x = 1.24

$result = $x - floor($x);

echo $result; // .24

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

I finally figured out the right answer to this question today.

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration> 
                <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>${project.basedir}/src/main/resources/wsdl/FooService.wsdl</wsdl>
                        <wsdlLocation>classpath:wsdl/FooService.wsdl</wsdlLocation>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Notice that I have prefixed the value in wsdlLocation with classpath:. This tells the plugin that the wsdl will be on the classpath instead of an absolute path. Then it will generate code similar to this:

@WebServiceClient(name = "FooService", 
                  wsdlLocation = "classpath:wsdl/FooService.wsdl",
                  targetNamespace = "http://org/example/foo") 
public class Foo_Service extends Service {

    public final static URL WSDL_LOCATION;

    public final static QName SERVICE = new QName("http://org/example/foo", "Foo");
    public final static QName FooSOAPOverHTTP = new QName("http://org/example/foo", "Foo_SOAPOverHTTP");
    static {
        URL url = Foo_Service.class.getClassLoader().getResource("wsdl/FooService.wsdl");
        if (url == null) {
            java.util.logging.Logger.getLogger(Foo_Service.class.getName())
                .log(java.util.logging.Level.INFO, 
                     "Can not initialize the default wsdl from {0}", "classpath:wsdl/FooService.wsdl");
        }       
        WSDL_LOCATION = url;
    }

Note that this only works with version 2.4.1 or newer of the cxf-codegen-plugin.

What Scala web-frameworks are available?

Both Sweet and Slinky seem to be unmaintanted for about a year. Sweet Maven repo sweetsoftwaredesign.com is dead so there's even no way to download dependencies.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

We managed it via the http.conf file (edited and then restarted the HTTP service):

<Directory "/home/the directory_where_your_serverside_pages_is">
    Header set Access-Control-Allow-Origin "*"
    AllowOverride all
    Order allow,deny
    Allow from all
</Directory>

In the Header set Access-Control-Allow-Origin "*", you can put a precise URL.

SQL Server error on update command - "A severe error occurred on the current command"

A different scenario but the same error: I got this error when I was trying to insert records into a temporary table using a stored procedure. It turned out there was a parameter mismatch. I was trying to insert a BIGINT into an INT.

Credit goes to Vicky Harp: http://vickyharp.com/2012/03/troubleshooting-a-severe-error-occurred-on-the-current-command/

How to get the current logged in user Id in ASP.NET Core

For getting current user id in razor views, we can inject UserManager in the view like this:

@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ string userId = _userManager.GetUserId(User); }

I hope you find it useful.

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

I have struggled with this for a long time, until I came across the cppreference.com explanation of the value categories.

It is actually rather simple, but I find that it is often explained in a way that's hard to memorize. Here it is explained very schematically. I'll quote some parts of the page:

Primary categories

The primary value categories correspond to two properties of expressions:

  • has identity: it's possible to determine whether the expression refers to the same entity as another expression, such as by comparing addresses of the objects or the functions they identify (obtained directly or indirectly);

  • can be moved from: move constructor, move assignment operator, or another function overload that implements move semantics can bind to the expression.

Expressions that:

  • have identity and cannot be moved from are called lvalue expressions;
  • have identity and can be moved from are called xvalue expressions;
  • do not have identity and can be moved from are called prvalue expressions;
  • do not have identity and cannot be moved from are not used.

lvalue

An lvalue ("left value") expression is an expression that has identity and cannot be moved from.

rvalue (until C++11), prvalue (since C++11)

A prvalue ("pure rvalue") expression is an expression that does not have identity and can be moved from.

xvalue

An xvalue ("expiring value") expression is an expression that has identity and can be moved from.

glvalue

A glvalue ("generalized lvalue") expression is an expression that is either an lvalue or an xvalue. It has identity. It may or may not be moved from.

rvalue (since C++11)

An rvalue ("right value") expression is an expression that is either a prvalue or an xvalue. It can be moved from. It may or may not have identity.

Speed up rsync with Simultaneous/Concurrent File Transfers?

rsync transfers files as fast as it can over the network. For example, try using it to copy one large file that doesn't exist at all on the destination. That speed is the maximum speed rsync can transfer data. Compare it with the speed of scp (for example). rsync is even slower at raw transfer when the destination file exists, because both sides have to have a two-way chat about what parts of the file are changed, but pays for itself by identifying data that doesn't need to be transferred.

A simpler way to run rsync in parallel would be to use parallel. The command below would run up to 5 rsyncs in parallel, each one copying one directory. Be aware that the bottleneck might not be your network, but the speed of your CPUs and disks, and running things in parallel just makes them all slower, not faster.

run_rsync() {
    # e.g. copies /main/files/blah to /main/filesTest/blah
    rsync -av "$1" "/main/filesTest/${1#/main/files/}"
}
export -f run_rsync
parallel -j5 run_rsync ::: /main/files/*

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Identify if a string is a number

I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

Simple to use:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

Or to test a potential Hex string, you could use:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

The optional 'culture' parameter can be used in much the same way.

It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.

Using "margin: 0 auto;" in Internet Explorer 8

As explained by buti-oxa this is a bug with the way IE8 handles replaced elements. If you don't want to add an explicit width to your button then you can change it to an inline-block and center align the contents:

<div style="height: 500px; width: 500px; background-color: Yellow; text-align: center;">
  <input type="submit" style="display: inline-block;" />
</div>

If you want this to work in older versions of Mozilla (including FF2) that don't support inline-block then you can add display: -moz-inline-stack; to the button.

Getting Textarea Value with jQuery

By using new version of jquery (1.8.2), I amend the current code like in this links http://jsfiddle.net/q5EXG/97/

By using the same code, I just change from jQuery to '$'

<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>

$('#send-thoughts').click(function()
{ var thought = $('#message').val();
  alert(thought);
});

How to clear APC cache entries?

If you want to monitor the results via json, you can use this kind of script:

<?php

$result1 = apc_clear_cache();
$result2 = apc_clear_cache('user');
$result3 = apc_clear_cache('opcode');
$infos = apc_cache_info();
$infos['apc_clear_cache'] = $result1;
$infos["apc_clear_cache('user')"] = $result2;
$infos["apc_clear_cache('opcode')"] = $result3;
$infos["success"] = $result1 && $result2 && $result3;
header('Content-type: application/json');
echo json_encode($infos);

As mentioned in other answers, this script will have to be called via http or curl and you will have to be secured if it is exposed in the web root of your application. (by ip, token...)

Linking dll in Visual Studio

Assume that the source file you want to compile is main.cpp and your example_dll.dll and example_dll.lib . now run cl.exe main.cpp /EHsc /link example_dll.lib now you may get main.exe

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

Where does Anaconda Python install on Windows?

This one is easy. When you start the installation, Anaconda asks "Destination Folder" as below screenshot. If you are not sure where did default installation go, double click setup file and see what anaconda offers as a default location.
Anaconda image

How to reset a select element with jQuery

The best javascript solution I've found is this

elm.options[0].selected="selected";

Calculating distance between two points, using latitude longitude?

Here is a page with javascript examples for various spherical calculations. The very first one on the page should give you what you need.

http://www.movable-type.co.uk/scripts/latlong.html

Here is the Javascript code

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad(); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
        Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

Where 'd' will hold the distance.

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

WCF gives an unsecured or incorrectly secured fault error

Mostly this exception happens when there is some errors in the server, the most common one is a wrong configuration of the authentication database, or authentication. In my case there was different clock synchronization make sure both client and server have same settings

Click on Time at your Right-Bottom side -> "Change date time settings..." -> "Internet Time" tab -> Change Settings... -> check the "Synchronise with an internet time server" option if it is unchecked -> from server dropdown select "times.windows.com" -> Update Now -> OK

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature

Text is used to store large string.

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

Decimal values in SQL for dividing results

You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx

For example

DECLARE @num1 int = 3 DECLARE @num2 int = 2

SELECT @num1/@num2

SELECT @num1/CONVERT(decimal(4,2), @num2)

The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000

How to build query string with Javascript

You don't actually need a form to do this with Prototype. Just use Object.toQueryString function:

Object.toQueryString({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })

// -> 'action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'

In MVC, how do I return a string result?

There Are 2 ways to return a string from the controller to the view:

First

You could return only the string, but it will not be included in your .cshtml file. it will be just a string appearing in your browser.


Second

You could return a string as the Model object of View Result.

Here is the code sample to do this:

public class HomeController : Controller
{
    // GET: Home
    // this will return just a string, not html
    public string index()
    {
        return "URL to show";
    }

    public ViewResult AutoProperty()
    {   
        string s = "this is a string ";
        // name of view , object you will pass
        return View("Result", s);

    }
}

In the view file to run AutoProperty, It will redirect you to the Result view and will send s
code to the view

<!--this will make this file accept string as it's model-->
@model string

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Result</title>
</head>
<body>
    <!--this will represent the string -->
    @Model
</body>
</html>

I run this at http://localhost:60227/Home/AutoProperty.

MongoDb query condition on comparing 2 fields

You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );

or more compact:

db.T.find( { $where : "this.Grade1 > this.Grade2" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

Configuration with name 'default' not found. Android Studio

Your module name must be camelCase eg. pdfLib. I had same issue because I my module name was 'PdfLib' and after renaming it to 'pdfLib'. It worked. The issue was not in my device but in jenkins server. So, check and see if you have such modulenames

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

Detecting scroll direction

You can try doing this.

_x000D_
_x000D_
function scrollDetect(){_x000D_
  var lastScroll = 0;_x000D_
_x000D_
  window.onscroll = function() {_x000D_
      let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value_x000D_
_x000D_
      if (currentScroll > 0 && lastScroll <= currentScroll){_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";_x000D_
      }else{_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling UP";_x000D_
      }_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
scrollDetect();
_x000D_
html,body{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
_x000D_
.cont{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  background: #ffad33;_x000D_
}_x000D_
_x000D_
.red{_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
p{_x000D_
  position:fixed;_x000D_
  font-size:25px;_x000D_
  top:5%;_x000D_
  left:5%;_x000D_
}
_x000D_
<div class="cont">_x000D_
  <div class="item"></div>_x000D_
  <div class="item red"></div>_x000D_
  <p id="scrollLoc">0</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Check if value exists in dataTable?

You should be able to use the DataTable.Select() method. You can us it like this.

if(myDataTable.Select("Author = '" + AuthorName.Replace("'","''") + '").Length > 0)
    ...

The Select() funciton returns an array of DataRows for the results matching the where statement.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

We have come across this issue in desktop app.

Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.

enter image description here

Finding CN of users in Active Directory

You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.

alt text

Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement namespace, you could also do it programmatically:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.

Or:

UserPrincipal myself = UserPrincipal.Current;

This will give you a UserPrincipal object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!

Position DIV relative to another DIV?

You want to use position: absolute while inside the other div.

DEMO

How to update attributes without validation

try using

@record.assign_attributes({ ... })
@record.save(validate: false)

works for me

How do you add a Dictionary of items into another Dictionary

Swift 4 provides merging(_:uniquingKeysWith:), so for your case:

let combinedDict = dict1.merging(dict2) { $1 }

The shorthand closure returns $1, therefore dict2's value will be used when there is a conflict with the keys.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")