Programs & Examples On #Publisher policy

Header and footer in CodeIgniter

This question has been answered properly, but I would like to add my approach, it's not that different than what the others have mentioned.

I use different layouts pages to call different headers/footers, some call this layout, some call it template etc.

  1. Edit core/Loader.php and add your own function to load your layout, I called the function e.g.layout.

  2. Create your own template page and make it call header/footer for you, I called it default.php and put in a new directory e.g. view/layout/default.php

  3. Call your own view page from your controller as you would normally. But instead of calling $this-load->view use $this->load->layout, layout function will call the default.php and default.php will call your header and footer.

1) In core/Loader.php under view() function I duplicated it and added mine

   public function layout($view, $vars = array(), $return = FALSE)
   {
       $vars["display_page"] = $view;//will be called from the layout page
       $layout               = isset($vars["layout"]) ? $vars["layout"] : "default";
       return $this->_ci_load(array('_ci_view' => "layouts/$layout", '_ci_vars' =>  $this->_ci_object_to_array($vars), '_ci_return' => $return));
   }

2) Create layout folder and put default.php in it in view/layout/default.php

   $this->load->view('parts/header');//or wherever your header is
   $this->load->view($display_page);
   $this->load->view('parts/footer');or wherever your footer is

3) From your controller, call your layout

 $this->load->layout('projects');// will use 'view/layout/default.php' layout which in return will call header and footer as well. 

To use another layout, include the new layout name in your $data array

 $data["layout"] = "full_width";
 $this->load->layout('projects', $data);// will use full_width.php layout

and of course you must have your new layout in the layout directory as in:

view/layout/full_width.php 

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

you have to add the missing local lang helper: for me the missing ones where de_LU de_LU.UTF-8 . Mongo 2.6.4 worked wihtout mongo 2.6.5 throw an error on this

How to use <md-icon> in Angular Material?

As the other answers didn't address my concern I decided to write my own answer.

The path given in the icon attribute of the md-icon directive is the URL of a .png or .svg file lying somewhere in your static file directory. So you have to put the right path of that file in the icon attribute. p.s put the file in the right directory so that your server could serve it.

Remember md-icon is not like bootstrap icons. Currently they are merely a directive that shows a .svg file.

Update

Angular material design has changed a lot since this question was posted.

Now there are several ways to use md-icon

The first way is to use SVG icons.

<md-icon md-svg-src = '<url_of_an_image_file>'></md-icon>

Example:

<md-icon md-svg-src = '/static/img/android.svg'></md-icon>

or

<md-icon md-svg-src = '{{ getMyIcon() }}'></md-icon>

:where getMyIcon is a method defined in $scope.

or <md-icon md-svg-icon="social:android"></md-icon>

to use this you have to the $mdIconProvider service to configure your application with svg iconsets.

angular.module('appSvgIconSets', ['ngMaterial'])  
  .controller('DemoCtrl', function($scope) {})  
  .config(function($mdIconProvider) {
    $mdIconProvider
      .iconSet('social', 'img/icons/sets/social-icons.svg', 24)
      .defaultIconSet('img/icons/sets/core-icons.svg', 24);    
  });

The second way is to use font icons.

<md-icon md-font-icon="android" alt="android"></md-icon>

<md-icon md-font-icon="fa-magic" class="fa" alt="magic wand"></md-icon>

prior to doing this you have to load the font library like this..

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or use font icons with ligatures

<md-icon md-font-library="material-icons">face</md-icon>

<md-icon md-font-library="material-icons">#xE87C;</md-icon>

<md-icon md-font-library="material-icons" class="md-light md-48">face</md-icon>

For further details check our

Angular Material mdIcon Directive documentation

$mdIcon Service Documentation

$mdIconProvider Service Documentation

How can I parse a JSON file with PHP?

It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].

[ // <-- Note that I changed this
    {
        "name" : "john", // And moved the name here.
        "status":"Wait"
    },
    {
        "name" : "Jennifer",
        "status":"Active"
    },
    {
        "name" : "James",
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
] // <-- And this.

With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.

Right align and left align text in same HTML table cell

It is possible but how depends on what you are trying to accomplish. If it's this:

| Left-aligned       Right-aligned | in one cell then you can use floating divs inside the td tag:

<td>
<div style='float: left; text-align: left'>Left-aligned</div>
<div style='float: right; text-align: right'>Right-aligned</div>
</td>

If it's | Left-aligned
                                           Right Aligned |

Then Balon's solution is correct.

If it's: | Left-aligned    |   Right-Aligned |

Then it's:

<td align="left">Left-aligned</td>
<td align="right">Right-Aligned</td>

Firefox 'Cross-Origin Request Blocked' despite headers

To debug, check server logs if possible. Firefox returns CORS errors in console for a whole range of reasons.

One of the reasons is also uMatrix (and I guess NoScript and similar too) plugin.

XPath with multiple conditions

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

Cannot find pkg-config error

Answer to my question (after several Google searches) revealed the following:

$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install

from the following link: Link showing above

Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!

Doing this fixed my issues as mentioned above.

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

Difference between SurfaceView and View?

The main difference is that SurfaceView can be drawn on by background theads but Views can't. SurfaceViews use more resources though so you don't want to use them unless you have to.

Tree data structure in C#

In case you need a rooted tree data structure implementation that uses less memory, you can write your Node class as follows (C++ implementation):

class Node {
       Node* parent;
       int item; // depending on your needs

       Node* firstChild; //pointer to left most child of node
       Node* nextSibling; //pointer to the sibling to the right
}

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

The solutions posted here did not work well for me, so I did a mixture of the ones of this question and the following question: Is it possible to create multi-level ordered list in HTML?

/* Numbered lists like 1, 1.1, 2.2.1... */
ol li {display:block;} /* hide original list counter */
ol > li:first-child {counter-reset: item;} /* reset counter */
ol > li {counter-increment: item; position: relative;} /* increment counter */
ol > li:before {content:counters(item, ".") ". "; position: absolute; margin-right: 100%; right: 10px;} /* print counter */

Result:

screenshot

Note: the screenshot, if you wish to see the source code or whatever is from this post: http://estiloasertivo.blogspot.com.es/2014/08/introduccion-running-lean-y-lean.html

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

This one also works

  1. Remove the "php.executablePath" line from the VS code settings.

  2. Then add the xampp php path to the System variables

enter image description here

enter image description here

After that restart the Visual Studio Code

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?

Yes.

Create the .o (as per normal):

g++ -c header.cpp

Create the archive:

ar rvs header.a header.o

Test:

g++ test.cpp header.a -o executable_name

Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:

g++ test.cpp header.cpp -o executable_name

Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.

Hope this helps!

Validation of radio button group using jQuery validation plugin

I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:

        'highlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
                    $(this).addClass(errorClass);
                });
            } else {
                $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
                $(element).addClass(errorClass);
            }
        },
        'unhighlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
                    $(this).removeClass(errorClass);
                });
            }else {
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                $(element).removeClass(errorClass);
            }
        },

How to add color to Github's README.md file

It's worth mentioning that you can add some colour in a README using a placeholder image service. For example if you wanted to provide a list of colours for reference:

- ![#f03c15](https://via.placeholder.com/15/f03c15/000000?text=+) `#f03c15`
- ![#c5f015](https://via.placeholder.com/15/c5f015/000000?text=+) `#c5f015`
- ![#1589F0](https://via.placeholder.com/15/1589F0/000000?text=+) `#1589F0`

Produces:

  • #f03c15 #f03c15
  • #c5f015 #c5f015
  • #1589F0 #1589F0

How can I get a list of Git branches, ordered by most recent commit?

I use the following alias:

recent = "!r(){git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'}; r"

which produces:

Result

Use '|' to separate.

How to read from standard input in the console?

Always try to use the bufio.NewScanner for collecting input from the console. As others mentioned, there are multiple ways to do the job but Scanner is originally intended to do the job. Dave Cheney explains why you should use Scanner instead of bufio.Reader's ReadLine.

https://twitter.com/davecheney/status/604837853344989184?lang=en

Here is the code snippet answer for your question

package main

import (
    "bufio"
    "fmt"
    "os"
)

/*
 Three ways of taking input
   1. fmt.Scanln(&input)
   2. reader.ReadString()
   3. scanner.Scan()

   Here we recommend using bufio.NewScanner
*/

func main() {
    // To create dynamic array
    arr := make([]string, 0)
    scanner := bufio.NewScanner(os.Stdin)
    for {
        fmt.Print("Enter Text: ")
        // Scans a line from Stdin(Console)
        scanner.Scan()
        // Holds the string that scanned
        text := scanner.Text()
        if len(text) != 0 {
            fmt.Println(text)
            arr = append(arr, text)
        } else {
            break
        }

    }
    // Use collected inputs
    fmt.Println(arr)
}

If you don't want to programmatically collect the inputs, just add these lines

   scanner := bufio.NewScanner(os.Stdin)
   scanner.Scan()
   text := scanner.Text()
   fmt.Println(text)

The output of above program will be:

Enter Text: Bob
Bob
Enter Text: Alice
Alice
Enter Text:
[Bob Alice]

Above program collects the user input and saves them to an array. We can also break that flow with a special character. Scanner provides API for advanced usage like splitting using a custom function etc, scanning different types of I/O streams(Stdin, String) etc.

What's the difference between an argument and a parameter?

Parameters are variables that are used to store the data that's passed into a function for the function to use. Arguments are the actual data that's passed into a function when it is invoked:

// x and y are parameters in this function declaration
function add(x, y) {
  // function body
  var sum = x + y;
  return sum; // return statement
}

// 1 and 2 are passed into the function as arguments
var sum = add(1, 2);

How to start Fragment from an Activity

In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.

   class FragmentA extends Fragment{
    public static FragmentA newInstance(YourDataClass data) {

            FragmentA f = new FragmentA();
            Bundle b = new Bundle();
            b.putString("data", data);
            f.setArguments(b);

            return f;
        }
    }

In order to start the fragment from the class, you can do the following

 Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

However, the data class must be parceable or serializable.

For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience

https://developer.android.com/guide/components/fragments#java

Using global variables between files?

You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.

A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.

So, in your example:

# ../myproject/main.py

# Define global myList
# global myList  - there is no "global" declaration at module level. Just inside
# function and methods
myList = []

# Imports
import subfile

# Do something
subfile.stuff()
print(myList[0])

And:

# ../myproject/subfile.py

# Save "hey" into myList
def stuff():
     # You have to make the module main available for the 
     # code here.
     # Placing the import inside the function body will
     # usually avoid import cycles - 
     # unless you happen to call this function from 
     # either main or subfile's body (i.e. not from inside a function or method)
     import main
     main.mylist.append("hey")

Convert Array to Object

ES5 - Solution:

Using Array prototype function 'push' and 'apply' you can populate the object with the array elements.

_x000D_
_x000D_
var arr = ['a','b','c'];_x000D_
var obj = new Object();_x000D_
Array.prototype.push.apply(obj, arr);_x000D_
console.log(obj);    // { '0': 'a', '1': 'b', '2': 'c', length: 3 }_x000D_
console.log(obj[2]); // c
_x000D_
_x000D_
_x000D_

Set the layout weight of a TextView programmatically

TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

The network path was not found

This is probably related to your database connection string or something like that.

I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).

I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)

Better techniques for trimming leading zeros in SQL Server?

In MySQL you can do this...

Trim(Leading '0' from your_column)

How to disable Excel's automatic cell reference change after copy/paste?

I think that you're stuck with the workaround you mentioned in your edit.

I would start by converting every formula on the sheet to text roughly like this:

Dim r As Range

For Each r In Worksheets("Sheet1").UsedRange
    If (Left$(r.Formula, 1) = "=") Then
        r.Formula = "'ZZZ" & r.Formula
    End If
Next r

where the 'ZZZ uses the ' to signify a text value and the ZZZ as a value that we can look for when we want to convert the text back to being a formula. Obviously if any of your cells actually start with the text ZZZ then change the ZZZ value in the VBA macro to something else

When the re-arranging is complete, I would then convert the text back to a formula like this:

For Each r In Worksheets("Sheet1").UsedRange
    If (Left$(r.Formula, 3) = "ZZZ") Then
        r.Formula = Mid$(r.Formula, 4)
    End If
Next r

One real downside to this method is that you can't see the results of any formula while you are re-arranging. You may find that when you convert back from text to formula that you have a slew of #REF errors for example.

It might be beneficial to work on this in stages and convert back to formulas every so often to check that no catastrophes have occurred

LINQ .Any VS .Exists - What's the difference?

When you correct the measurements - as mentioned above: Any and Exists, and adding average - we'll get following output:

Executing search Exists() 1000 times ... 
Average Exists(): 35566,023
Fastest Exists() execution: 32226 

Executing search Any() 1000 times ... 
Average Any(): 58852,435
Fastest Any() execution: 52269 ticks

Benchmark finished. Press any key.

How to completely uninstall Visual Studio 2010?

Update April 2016 - for VS2013+

Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.

They abandoned the solution for a while; however work has begun again again as of April 2016.

There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".


Original Answer - for VS2010, VS2012

Note that the following two solutions still leave traces (such as registry files) and can't really be considered a 'clean' uninstall (see the final section of the answer for a completely clean solution).


Solution 1 - for: VS 2010

There's an uninstaller provided by Microsoft called the Visual Studio 2010 Uninstall Utility. It comes with three options:

  1. Default (VS2010_Uninstall-RTM.ENU.exe)
  2. Full (VS2010_Uninstall-RTM.ENU.exe /full)
  3. Complete (VS2010_Uninstall-RTM.ENU.exe /full /netfx)

The above link explains the uninstaller in greater detail - I recommend reading the comments on the article before using it as some have noted problems (and workarounds) when service packs are installed. Afterwards, use something like CCleaner to remove the leftover registry files.

Here is the link to the download page of the VS2010 UU.


Solution 2 - for: VS 2010, VS 2012

Microsoft provide an uninstall /force feature that removes most remnants of either VS2010 or VS2012 from your computer.

MSDN: How to uninstall Visual Studio 2010/2012. From the link:

Warning: Running this command may remove some packages even if they are still in use like those listed in Optional shared packages.

  1. Download the setup application you used to originally install Visual Studio 2012. If you installed from media, please insert that media.
  2. Open a command prompt. Click Run on the Start menu (Start + R). Type cmd and press OK (Enter).
  3. Type in the full path to the setup application and pass the following command line switches: /uninstall /force Example: D:\vs_ultimate.exe /uninstall /force
  4. Click the Uninstall button and follow the prompts.

Afterwards, use something like CCleaner to remove the leftover registry files.


A completely clean uninstall?

Sadly, the only (current) way to achieve this is to follow dnLL's advice in their answer and perform a complete operating system reinstall. Then, in future, you could use Visual Studio inside a Virtual Machine instead and not have to worry about these issues again.

How exactly does the python any() function work?

Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

Javascript add method to object

This all depends on how you're creating Foo, and how you intend to use .bar().

First, are you using a constructor-function for your object?

var myFoo = new Foo();

If so, then you can extend the Foo function's prototype property with .bar, like so:

function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };

var myFoo = new Foo();
myFoo.bar();

In this fashion, each instance of Foo now has access to the SAME instance of .bar.
To wit: .bar will have FULL access to this, but will have absolutely no access to variables within the constructor function:

function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };

var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
             // ...or a value of `secret` in a higher/global scope

In another way, you could define a function to return any object (not this), with .bar created as a property of that object:

function giveMeObj () {
    var private = 42,
        privateBar = function () { console.log(private); },
        public_interface = {
            bar : privateBar
        };

    return public_interface;
}

var myObj = giveMeObj();
myObj.bar(); // 42

In this fashion, you have a function which creates new objects.
Each of those objects has a .bar function created for them.
Each .bar function has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .bar still has access to this as well, as this, when you call the function like myObj.bar(); will always refer to myObj (public_interface, in my example Foo).

The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar, which will eat into memory.

You could also do this inside of a constructor function, setting this.bar = function () {}; inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.

So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through this or myObj.X)?

and the second question is: Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?

For example, if you gave every triangle and every texture their own .draw function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...

If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

Are "while(true)" loops so bad?

Back in 1967, Edgar Dijkstra wrote an article in a trade magazine about why goto should be eliminated from high level languages to improve code quality. A whole programming paradigm called "structured programming" came out of this, though certainly not everyone agrees that goto automatically means bad code.

The crux of structured programming is essentially that the structure of the code should determine its flow rather than having gotos or breaks or continues to determine flow, wherever possible. Similiarly, having multiple entry and exit points to a loop or function are also discouraged in that paradigm.

Obviously this is not the only programming paradigm, but often it can be easily applied to other paradigms like object oriented programming (ala Java).

Your teachers has probably been taught, and is trying to teach your class that we would best avoid "spaghetti code" by making sure our code is structured, and following the implied rules of structured programming.

While there is nothing inherently "wrong" with an implementation that uses break, some consider it significantly easier to read code where the condition for the loop is explicitly specified within the while() condition, and eliminates some possibilities of being overly tricky. There are definitely pitfalls to using a while(true) condition that seem to pop up frequently in code by novice programmers, such as the risk of accidentally creating an infinite loop, or making code that is hard to read or unnecessarily confusing.

Ironically, exception handling is an area where deviation from structured programming will certainly come up and be expected as you get further into programming in Java.

It is also possible your instructor may have expected you to demonstrate your ability to use a particular loop structure or syntax being taught in that chapter or lesson of your text, and while the code you wrote is functionally equivalent, you may not have been demonstrating the particular skill you were supposed to be learning in that lesson.

Compare two files in Visual Studio

In Visual Studio the Diff can be called using Command Window and then Tools.DiffFiles command

  1. Open Command Window by hotkeys Ctrl + W, A or by menu View -> Other Windows -> Command Window
  2. Enter command Tools.DiffFiles "FirstFile.cs" "SecondFile.cs"

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

I run into this error when I tried to install Python 3.7.3 in Ubuntu 18.04 with next command: $ pyenv install 3.7.3. Installation succeeded after running $ sudo apt-get update && sudo apt-get install libffi-dev (as suggested here). The issue was solved there.

How to use multiprocessing pool.map with multiple arguments?

A better way is using decorator instead of writing wrapper function by hand. Especially when you have a lot of functions to map, decorator will save your time by avoiding writing wrapper for every function. Usually a decorated function is not picklable, however we may use functools to get around it. More disscusions can be found here.

Here the example

def unpack_args(func):
    from functools import wraps
    @wraps(func)
    def wrapper(args):
        if isinstance(args, dict):
            return func(**args)
        else:
            return func(*args)
    return wrapper

@unpack_args
def func(x, y):
    return x + y

Then you may map it with zipped arguments

np, xlist, ylist = 2, range(10), range(10)
pool = Pool(np)
res = pool.map(func, zip(xlist, ylist))
pool.close()
pool.join()

Of course, you may always use Pool.starmap in Python 3 (>=3.3) as mentioned in other answers.

How to check if an integer is in a given range?

Google's Java Library Guava also implements Range:

import com.google.common.collect.Range;

Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false

Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true

Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true

select2 - hiding the search box

//Disable a search on particular selector
$(".my_selector").select2({
    placeholder: "ÁREAS(todas)",
    tags: true,
    width:'100%',
    containerCssClass: "area_disable_search_input" // I add new class 
});

//readonly prop to selector class
$(".area_disable_search_input input").prop("readonly", true);

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

I strongly recommend to use a Maven Repository Manager such as Nexus. It will help you to get stable and reproducible builds with Maven. As the Repository Manager is usually in your LAN, you don't have to configure the proxy settings, but you need to define some other configurations:

http://www.sonatype.com/books/nexus-book/reference/maven-sect-single-group.html

http://maven.apache.org/repository-management.html

How to enable mod_rewrite for Apache 2.2

Use below command

sudo a2enmod rewrite

And the restart apache through below command

sudo service apache2 restart

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

How can I find a file/directory that could be anywhere on linux command line?

To get rid of permission errors (and such), you can redirect stderr to nowhere

find / -name "something" 2>/dev/null

Store List to session

public class ProductList
{
   public string product{get;set;}
   public List<ProductList> objList{get;set;}
}

ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});

now assign obj to session

Session["Product"]=obj;

for retrieval of session.

ProductList objLst = (ProductList)Session["Product"];

Javascript: Extend a Function

This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.

First let us extend javascript function.

function Base(props) {
    const _props = props
    this.getProps = () => _props

    // We can make method private by not binding it to this object. 
    // Hence it is not exposed when we return this.
    const privateMethod = () => "do internal stuff" 

    return this
}

You can extend this function by creating child function in following way

function Child(props) {
    const parent = Base(props)
    this.getMessage = () => `Message is ${parent.getProps()}`;

    // You can remove the line below to extend as in private inheritance, 
    // not exposing parent function properties and method.
    this.prototype = parent
    return this
}

Now you can use Child function as follows,

let childObject = Child("Secret Message")
console.log(childObject.getMessage())     // logs "Message is Secret Message"
console.log(childObject.getProps())       // logs "Secret Message"

We can also create Javascript Function by extending Javascript classes, like this.

class BaseClass {
    constructor(props) {
        this.props = props
        // You can remove the line below to make getProps method private. 
        // As it will not be binded to this, but let it be
        this.getProps = this.getProps.bind(this)
    }

    getProps() {
        return this.props
    }
}

Let us extend this class with Child function like this,

function Child(props) {
    let parent = new BaseClass(props)
    const getMessage = () => `Message is ${parent.getProps()}`;
    return { ...parent, getMessage} // I have used spread operator. 
}

Again you can use Child function as follows to get similar result,

let childObject = Child("Secret Message")
console.log(childObject.getMessage())     // logs "Message is Secret Message"
console.log(childObject.getProps())       // logs "Secret Message"

Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.

How to check the version of scipy

on command line

 example$:python
 >>> import scipy
 >>> scipy.__version__
 '0.9.0'

How can I get stock quotes using Google Finance API?

Building upon the shoulders of giants...here's a one-liner I wrote to zap all of Google's current stock data into local Bash shell variables:

stock=$1 

# Fetch from Google Finance API, put into local variables
eval $(curl -s "http://www.google.com/ig/api?stock=$stock"|sed 's/</\n</g' |sed '/data=/!d; s/ data=/=/g; s/\/>/; /g; s/</GF_/g' |tee /tmp/stockprice.tmp.log)

echo "$stock,$(date +%Y-%m-%d),$GF_open,$GF_high,$GF_low,$GF_last,$GF_volume"

Then you will have variables like $GF_last $GF_open $GF_volume etc. readily available. Run env or see inside /tmp/stockprice.tmp.log

http://www.google.com/ig/api?stock=TVIX&output=csv by itself returns:

<?xml version="1.0"?>
<xml_api_reply version="1">
<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<symbol data="TVIX"/>
<pretty_symbol data="TVIX"/>
<symbol_lookup_url data="/finance?client=ig&amp;q=TVIX"/>
<company data="VelocityShares Daily 2x VIX Short Term ETN"/>
<exchange data="AMEX"/>
<exchange_timezone data="ET"/>
<exchange_utc_offset data="+05:00"/>
<exchange_closing data="960"/>
<divisor data="2"/>
<currency data="USD"/>
<last data="57.45"/>
<high data="59.70"/>
<low data="56.85"/>

etc.

So for stock="FBM" /tmp/stockprice.tmp.log (and your environment) will contain:

GF_symbol="FBM"; 
GF_pretty_symbol="FBM"; 
GF_symbol_lookup_url="/finance?client=ig&amp;q=FBM"; 
GF_company="Focus Morningstar Basic Materials Index ETF"; 
GF_exchange="NYSEARCA"; 
GF_exchange_timezone=""; 
GF_exchange_utc_offset=""; 
GF_exchange_closing=""; 
GF_divisor="2"; 
GF_currency="USD"; 
GF_last="22.82"; 
GF_high="22.82"; 
GF_low="22.82"; 
GF_volume="100"; 
GF_avg_volume=""; 
GF_market_cap="4.56"; 
GF_open="22.82"; 
GF_y_close="22.80"; 
GF_change="+0.02"; 
GF_perc_change="0.09"; 
GF_delay="0"; 
GF_trade_timestamp="8 hours ago"; 
GF_trade_date_utc="20120228"; 
GF_trade_time_utc="184541"; 
GF_current_date_utc="20120229"; 
GF_current_time_utc="033534"; 
GF_symbol_url="/finance?client=ig&amp;q=FBM"; 
GF_chart_url="/finance/chart?q=NYSEARCA:FBM&amp;tlf=12"; 
GF_disclaimer_url="/help/stock_disclaimer.html"; 
GF_ecn_url=""; 
GF_isld_last=""; 
GF_isld_trade_date_utc=""; 
GF_isld_trade_time_utc=""; 
GF_brut_last=""; 
GF_brut_trade_date_utc=""; 
GF_brut_trade_time_utc=""; 
GF_daylight_savings="false"; 

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

SELECT 
    p1.kArtikel, 
    p1.cName, 
    p1.cKurzBeschreibung, 
    p1.dLetzteAktualisierung, 
    p1.dErstellt, 
    p1.cSeo,
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad  
FROM 
    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
WHERE
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
ORDER BY 
  p1.kArtikel DESC
LIMIT
    100;

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

Replace words in a string - Ruby

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

Set the absolute position of a view

Just to add to Andy Zhang's answer above, if you want to, you can give param to rl.addView, then make changes to it later, so:

params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

Could equally well be written as:

params = new RelativeLayout.LayoutParams(30, 40);
rl.addView(iv, params);
params.leftMargin = 50;
params.topMargin = 60;

So if you retain the params variable, you can change the layout of iv at any time after adding it to rl.

Javascript seconds to minutes and seconds

I was thinking of a faster way to get this done and this is what i came up with

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

If we want to convert "time" to minutes and seconds, for example:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

git pull aborted with error filename too long

A few years late, but I'd like to add that if you need to do this in one fell swoop (like I did) you can set the config settings during the clone command. Try this:

git clone -c core.longpaths=true <your.url.here>

How to use a dot "." to access members of dictionary?

I recently came across the 'Box' library which does the same thing.

Installation command : pip install python-box

Example:

from box import Box

mydict = {"key1":{"v1":0.375,
                    "v2":0.625},
          "key2":0.125,
          }
mydict = Box(mydict)

print(mydict.key1.v1)

I found it to be more effective than other existing libraries like dotmap, which generate python recursion error when you have large nested dicts.

link to library and details: https://pypi.org/project/python-box/

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

jQuery get an element by its data-id

You can always use an attribute selector. The selector itself would look something like:

a[data-item-id=stand-out]

How do I convert a string to a number in PHP?

In addition to Boykodev's answer I suggest this:

Input             Output
'2' * 1           2 (int)
'2.34' * 1        2.34 (float)
'0.3454545' * 1   0.3454545 (float)

Switch with if, else if, else, and loops inside case

If you need the for statement to contain only the if, you need to remove its else, like this:

for(int i=0; i<something_in_the_array.length;i++)
    if(whatever_value==(something_in_the_array[i]))
    {
        value=2;
        break;
    }

    /*this "else" must go*/
    if(whatever_value==2)
    {
        value=3;
        break;
    }

    else if(whatever_value==3)
    {
        value=4;
        break;
    }

Convert base64 string to ArrayBuffer

For Node.js users:

const myBuffer = Buffer.from(someBase64String, 'base64');

myBuffer will be of type Buffer which is a subclass of Uint8Array. Unfortunately, Uint8Array is NOT an ArrayBuffer as the OP was asking for. But when manipulating an ArrayBuffer I almost always wrap it with Uint8Array or something similar, so it should be close to what's being asked for.

CodeIgniter htaccess and URL rewrite issues

Your .htaccess is slightly off. Look at mine:

 RewriteEngine On
 RewriteBase /codeigniter  

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
  RewriteRule ^(.*)$ /codeigniter/index.php?/$1 [L]

Notice "codeigniter" in two places.

after that, in your config:

base_url = "http://localhost/codeigniter"
index = ""

Change codeigniter to "ci" whereever appropriate

tar: add all files and directories in current directory INCLUDING .svn and so on

Don't create the tar file in the directory you are packing up:

tar -czf /tmp/workspace.tar.gz .

does the trick, except it will extract the files all over the current directory when you unpack. Better to do:

cd ..
tar -czf workspace.tar.gz workspace

or, if you don't know the name of the directory you were in:

base=$(basename $PWD)
cd ..
tar -czf $base.tar.gz $base

(This assumes that you didn't follow symlinks to get to where you are and that the shell doesn't try to second guess you by jumping backwards through a symlink - bash is not trustworthy in this respect. If you have to worry about that, use cd -P .. to do a physical change directory. Stupid that it is not the default behaviour in my view - confusing, at least, for those for whom cd .. never had any alternative meaning.)


One comment in the discussion says:

I [...] need to exclude the top directory and I [...] need to place the tar in the base directory.

The first part of the comment does not make much sense - if the tar file contains the current directory, it won't be created when you extract file from that archive because, by definition, the current directory already exists (except in very weird circumstances).

The second part of the comment can be dealt with in one of two ways:

  1. Either: create the file somewhere else - /tmp is one possible location - and then move it back to the original location after it is complete.
  2. Or: if you are using GNU Tar, use the --exclude=workspace.tar.gz option. The string after the = is a pattern - the example is the simplest pattern - an exact match. You might need to specify --exclude=./workspace.tar.gz if you are working in the current directory contrary to recommendations; you might need to specify --exclude=workspace/workspace.tar.gz if you are working up one level as suggested. If you have multiple tar files to exclude, use '*', as in --exclude=./*.gz.

Removing all non-numeric characters from string in Python

Just to add another option to the mix, there are several useful constants within the string module. While more useful in other cases, they can be used here.

>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

There are several constants in the module, including:

  • ascii_letters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
  • hexdigits (0123456789abcdefABCDEF)

If you are using these constants heavily, it can be worthwhile to covert them to a frozenset. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.

>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'

JSON post to Spring Controller

Convert your JSON object to JSON String using

JSON.stringify({"name":"testName"})

or manually. @RequestBody expecting json string instead of json object.

Note:stringify function having issue with some IE version, firefox it will work

verify the syntax of your ajax request for POST request. processData:false property is required in ajax request

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

Controller

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody -Covert Json object to java

@ResponseBody - convert Java object to json

error: package com.android.annotations does not exist

You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:

1- From the above menu go to edit configurations:

enter image description here

2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool

enter image description here

2- Fill the following information, note that the working directory is your project root directory (not the android directory):

enter image description here

3- Make sure this run before anything else, in the end, your configuration should look something like this: enter image description here

Permutation of array

According to wiki https://en.wikipedia.org/wiki/Heap%27s_algorithm

Heap's algorithm generates all possible permutations of n objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other n-2 elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.

So if we want to do it in recursive manner, Sudo code is bellow.

procedure generate(n : integer, A : array of any):
    if n = 1 then
          output(A)
    else
        for i := 0; i < n - 1; i += 1 do
            generate(n - 1, A)
            if n is even then
                swap(A[i], A[n-1])
            else
                swap(A[0], A[n-1])
            end if
        end for
        generate(n - 1, A)
    end if

java code:

public static void printAllPermutations(
        int n, int[] elements, char delimiter) {
    if (n == 1) {
        printArray(elements, delimiter);
    } else {
        for (int i = 0; i < n - 1; i++) {
            printAllPermutations(n - 1, elements, delimiter);
            if (n % 2 == 0) {
                swap(elements, i, n - 1);
            } else {
                swap(elements, 0, n - 1);
            }
        }
        printAllPermutations(n - 1, elements, delimiter);
    }
}

private static void printArray(int[] input, char delimiter) {
    int i = 0;
    for (; i < input.length; i++) {
        System.out.print(input[i]);
    }
    System.out.print(delimiter);
}

private static void swap(int[] input, int a, int b) {
    int tmp = input[a];
    input[a] = input[b];
    input[b] = tmp;
}

public static void main(String[] args) {
    int[] input = new int[]{0,1,2,3};
    printAllPermutations(input.length, input, ',');
}

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

How to check if a particular service is running on Ubuntu

for Centos 6.10 : /sbin/service serviceNAME status

for Centos 7.6 and ubuntu 18.04: systemctl status NAME.service

works for all of them: service --status-all

Define an alias in fish shell

If you add an abbr instead of an alias you'll get better auto-complete. In fish abbr more closely matches the behavior of a bash alias.

abbr -a gco git checkout

Will -add a new abbreviation gco that expands to git checkout.

Here's a video demo of the resulting auto-complete features

jQuery - Add active class and remove active from other element on click

You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/

$(".tab").removeClass("active");
$(this).addClass("active");  

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

What are the applications of binary trees?

One of the most important application of binary trees are balanced binary search trees like:

These type of trees have the property that the difference in heights of left subtree and right subtree is maintained small by doing operations like rotations each time a node is inserted or deleted.

Due to this, the overall height of the tree remains of the order of log n and the operations such as search, insertion and deletion of the nodes are performed in O(log n) time. The STL of C++ also implements these trees in the form of sets and maps.

Pass props to parent component in React.js

Edit: see the end examples for ES6 updated examples.

This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.

Other solutions are missing the point

While they still work fine, other answers are missing something very important.

Is there not a simple way to pass a child's props to its parent using events, in React.js?

The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?

Better implementation

Child: it really does not have to be more complicated than that.

var Child = React.createClass({
  render: function () {
    return <button onClick={this.props.onClick}>{this.props.text}</button>;
  },
});

Parent with single child: using the value it passes to the child

var Parent = React.createClass({
  getInitialState: function() {
     return {childText: "Click me! (parent prop)"};
  },
  render: function () {
    return (
      <Child onClick={this.handleChildClick} text={this.state.childText}/>
    );
  },
  handleChildClick: function(event) {
     // You can access the prop you pass to the children 
     // because you already have it! 
     // Here you have it in state but it could also be
     //  in props, coming from another parent.
     alert("The Child button text is: " + this.state.childText);
     // You can also access the target of the click here 
     // if you want to do some magic stuff
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.

var Parent = React.createClass({
  getInitialState: function() {
     return {childrenData: [
         {childText: "Click me 1!", childNumber: 1},
         {childText: "Click me 2!", childNumber: 2}
     ]};
  },
  render: function () {
    var children = this.state.childrenData.map(function(childData,childIndex) {
        return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
    }.bind(this));
    return <div>{children}</div>;
  },

  handleChildClick: function(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

It is also possible to use this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

Note we are binding with a null context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.

About encapsulation and coupling in other answers

This is for me a bad idea in term of coupling and encapsulation:

var Parent = React.createClass({
  handleClick: function(childComponent) {
     // using childComponent.props
     // using childComponent.refs.button
     // or anything else using childComponent
  },
  render: function() {
    <Child onClick={this.handleClick} />
  }
});

Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.

Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:

<Child ref="theChild" .../>

And access the DOM node in the parent with

React.findDOMNode(this.refs.theChild)

For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.

The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.

To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:

They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.

The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.

If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.

About using anything else

Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...) or childComponent.forceUpdate(), or assigning it new variables, inside the parent, making the whole app much harder to reason about.


Edit: ES6 examples

As many people now use ES6, here are the same examples for ES6 syntax

The child can be very simple:

const Child = ({
  onClick, 
  text
}) => (
  <button onClick={onClick}>
    {text}
  </button>
)

The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:

class Parent1 extends React.Component {
  handleChildClick(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
  render() {
    return (
      <div>
        {this.props.childrenData.map(child => (
          <Child
            key={child.childNumber}
            text={child.childText} 
            onClick={e => this.handleChildClick(child,e)}
          />
        ))}
      </div>
    );
  }
}

But it can also be simplified if it does not need to manage state:

const Parent2 = ({childrenData}) => (
  <div>
     {childrenData.map(child => (
       <Child
         key={child.childNumber}
         text={child.childText} 
         onClick={e => {
            alert("The Child button data is: " + child.childText + " - " + child.childNumber);
                    alert("The Child HTML is: " + e.target.outerHTML);
         }}
       />
     ))}
  </div>
)

JsFiddle


PERF WARNING (apply to ES5/ES6): if you are using PureComponent or shouldComponentUpdate, the above implementations will not be optimized by default because using onClick={e => doSomething()}, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this in class constructor) so that PureComponent optimization can kick in, or you can implement your own shouldComponentUpdate and ignore the callback in the props comparison check.

You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:

// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}

// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)

// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)

In this case you could optimize the Child component by using:

const OptimizedChild = onlyUpdateForKeys(['text'])(Child)

Using :after to clear floating elements

This will work as well:

.clearfix:before,
.clearfix:after {
    content: "";
    display: table;
} 

.clearfix:after {
    clear: both;
}

/* IE 6 & 7 */
.clearfix {
    zoom: 1;
}

Give the class clearfix to the parent element, for example your ul element.

Sources here and here.

How to filter Android logcat by application?

This is probably the simplest solution.

On top of a solution from Tom Mulcahy, you can further simplify it like below:

alias logcat="adb logcat | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`"

Usage is easy as normal alias. Just type the command in your shell:

logcat

The alias setup makes it handy. And the regex makes it robust for multi-process apps, assuming you care about the main process only.

Of coz you can set more aliases for each process as you please. Or use hegazy's solution. :)

In addition, if you want to set logging levels, it is

alias logcat-w="adb logcat *:W | grep `adb shell ps | egrep '\bcom.your.package.name\b' | cut -c10-15`"

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

ImageButton in Android

android:background="@drawable/eye"

works automatically.

android:src="@drawable/eye"

was what I used with all the problems of resizing the image the the width and height of the button...

JUnit Eclipse Plugin?

JUnit is part of Eclipse Java Development Tools (JDT). So, either install the JDT via Software Updates or download and install Eclipse IDE for Java Developers (actually, I'd recommend installing Eclipse IDE for Java EE Developers if you want a complete built-in environment for server side development).

You add it to a project by right clicking the project in the Package Explorer and selecting Build Path -> Add Libraries... Then simply select JUnit and click Next >.

Force encode from US-ASCII to UTF-8 (iconv)

People say you can't and I understand you may be frustrated when asking a question and getting such an answer.

If you really want it to show in UTF-8 instead of US ASCII then you need to do it in two steps.

First:

iconv -f us-ascii -t utf-16 yourfile > youfileinutf16.*

Second:

iconv -f utf-16le -t utf-8 yourfileinutf16 > yourfileinutf8.*

Then if you do a file -i, you'll see the new character set is UTF-8.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a poor name for a really useful concept.

The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is Bjarne Stroustrup's explanation of the topic.

A common use for RAII is locking a mutex:

// A class with implements RAII
class lock
{
    mutex &m_;

public:
    lock(mutex &m)
      : m_(m)
    {
        m.acquire();
    }
    ~lock()
    {
        m_.release();
    }
};

// A class which uses 'mutex' and 'lock' objects
class foo
{
    mutex mutex_; // mutex for locking 'foo' object
public:
    void bar()
    {
        lock scopeLock(mutex_); // lock object.

        foobar(); // an operation which may throw an exception

        // scopeLock will be destructed even if an exception
        // occurs, which will release the mutex and allow
        // other functions to lock the object and run.
    }
};

RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to Mike B for pointing this out.)

For those familliar with C# or VB.NET, you may recognize that RAII is similar to .NET deterministic destruction using IDisposable and 'using' statements. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.

 

† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.

Maintain aspect ratio of div but fill screen width and height in CSS?

I understand that you asked that you would like a CSS specific solution. To keep the aspect ratio, you would need to divide the height by the desired aspect ratio. 16:9 = 1.777777777778.

To get the correct height for the container, you would need to divide the current width by 1.777777777778. Since you can't check the width of the container with just CSS or divide by a percentage is CSS, this is not possible without JavaScript (to my knowledge).

I've written a working script that will keep the desired aspect ratio.

HTML

<div id="aspectRatio"></div>

CSS

body { width: 100%; height: 100%; padding: 0; margin: 0; }
#aspectRatio { background: #ff6a00; }

JavaScript

window.onload = function () {
    //Let's create a function that will scale an element with the desired ratio
    //Specify the element id, desired width, and height
    function keepAspectRatio(id, width, height) {
        var aspectRatioDiv = document.getElementById(id);
        aspectRatioDiv.style.width = window.innerWidth;
        aspectRatioDiv.style.height = (window.innerWidth / (width / height)) + "px";
    }

    //run the function when the window loads
    keepAspectRatio("aspectRatio", 16, 9);

    //run the function every time the window is resized
    window.onresize = function (event) {
        keepAspectRatio("aspectRatio", 16, 9);
    }
}

You can use the function again if you'd like to display something else with a different ratio by using

keepAspectRatio(id, width, height);

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

How to git ignore subfolders / subdirectories?

You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:

Debug/
Release/

This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.

Perl: Use s/ (replace) and return new string

If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s/// should be all you need:

#!/usr/bin/perl -w    

use strict;     

   main();   

   sub main{    
      my $foo = "blahblahblah";          
      print '$foo: ' , replace("lah","ar",$foo) , "\n";  #$foo: barbarbar

   }        

   sub replace {
      my ($from,$to,$string) = @_;
      $string =~s/$from/$to/ig;                          #case-insensitive/global (all occurrences)

      return $string;
   }

How to get all enum values in Java?

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

How can I create and style a div using JavaScript?

You can create like this

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"

document.getElementById("main").appendChild(board);

Complete Runnable Snippet:

_x000D_
_x000D_
var board;_x000D_
board= document.createElement("div");_x000D_
board.id = "mainBoard";_x000D_
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"_x000D_
    _x000D_
document.getElementById("main").appendChild(board);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

How to add a second css class with a conditional value in razor MVC 4

I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:

Your answer (assuming this works, I haven't tried this):

<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">

Second option:

@if (Model.Details.Count > 0) {
    <div class="details show">
}
else {
    <div class="details hide">
}

Third option:

<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">

How to import existing *.sql files in PostgreSQL 8.4?

Always preferred using a connection service file (lookup/google 'psql connection service file')

Then simply:

psql service={yourservicename} < {myfile.sql}

Where yourservicename is a section name from the service file.

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

Remove Blank option from Select Option with AngularJS

Finally it worked for me.

<select ng-init="mybasketModel = basket[0]" ng-model="mybasketModel">
        <option ng-repeat="item in basket" ng-selected="$first">{{item}}</option>
</select>


Create a custom View by inflating a layout?

Here is a simple demo to create customview (compoundview) by inflating from xml

attrs.xml

<resources>

    <declare-styleable name="CustomView">
        <attr format="string" name="text"/>
        <attr format="reference" name="image"/>
    </declare-styleable>
</resources>

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        ConstraintLayout(context, attrs, defStyleAttr) {

    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        View.inflate(context, R.layout.custom_layout, this)

        val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        try {
            val text = ta.getString(R.styleable.CustomView_text)
            val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
            if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
            }
            text_title.text = text
        } finally {
            ta.recycle()
        }
    }
}

custom_layout.xml

We should use merge here instead of ConstraintLayout because

If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="ContentDescription"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@id/image_thumb"
        app:layout_constraintStart_toStartOf="@id/image_thumb"
        app:layout_constraintTop_toBottomOf="@id/image_thumb"
        tools:text="Text" />

</merge>

Using activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f00"
        app:image="@drawable/ic_android"
        app:text="Android" />

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        app:image="@drawable/ic_adb"
        app:text="ADB" />

</LinearLayout>

Result

enter image description here

Github demo

how can I debug a jar at runtime?

http://www.eclipsezone.com/eclipse/forums/t53459.html

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044

The application, at launch, will wait until you connect from another source.

Why should I use a container div in HTML?

Most of the browser are taking web page size by default. So, sometime page will not display same in different browser. So, by using user can change for specific HTML element. For example, user can add margin, size, width, height etc of specific HTML tag.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

You are missing permission to create /var/run/mysqld directory.So please create and give permission as following.

  • mkdir -p /var/run/mysqld
  • chown mysql:mysql /var/run/mysqld

Change the project theme in Android Studio?

In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MyActivity2"
        android:label="@string/title_activity_my_activity2"
        android:theme="@style/myDialog"
        >
    </activity>
</application>

styles.xml example

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
    <!-- Customize your theme here. -->
</style>

<style name="myDialog" parent="android:Theme.Dialog">

</style>

In parent you set actualy the theme

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

Alternative to iFrames with HTML5

You should have a look into JSON-P - that was a perfect solution for me when I had that problem:

https://en.wikipedia.org/wiki/JSONP

You basically define a javascript file that loads all your data and another javascript file that processes and displays it. That gets rid of the ugly scrollbar of iframes.

Load HTML page dynamically into div with jQuery

You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a

How to sort by dates excel?

  1. Select the whole column
  2. Right click -> Format cells... -> Number -> Category: Date -> OK
  3. Data -> Text to Columns -> select Delimited -> Next -> in your case selection of Delimiters doesn't matter -> Next -> select Date: DMY -> Finish

Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest

How to create CSV Excel file C#?

The original class have a problem, and that is if you want to add a new column, you will receive KeyNotFoundException on Export method. For example:

static void Main(string[] args)
{
    var export = new CsvExport();

    export.AddRow();
    export["Region"] = "New York, USA";
    export["Sales"] = 100000;
    export["Date Opened"] = new DateTime(2003, 12, 31);

    export.AddRow();
    export["Region"] = "Sydney \"in\" Australia";
    export["Sales"] = 50000;
    export["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);
    export["Balance"] = 3.45f;  //Exception is throwed for this new column

    export.ExportToFile("Somefile.csv");
}

To solve this, and using the @KeyboardCowboy idea of ??using reflection, I modified the code to allow add rows that do not have the same columns. You can use instances of anonymous classes. For example:

static void Main(string[] args)
{
    var export = new CsvExporter();

    export.AddRow(new {A = 12, B = "Empty"});
    export.AddRow(new {A = 34.5f, D = false});

    export.ExportToFile("File.csv");
}

You can download the source code here CsvExporter. Feel free to use and modify.

Now, if all rows you want to write are of the same class, I created the generic class CsvWriter.cs, which has a better performance RAM usage and ideal for writing large files.Plus it lets you add formatters to the data type you want. An example of use:

class Program
{
    static void Main(string[] args)
    {
        var writer = new CsvWriter<Person>("Persons.csv");

        writer.AddFormatter<DateTime>(d => d.ToString("MM/dd/yyyy"));

        writer.WriteHeaders();
        writer.WriteRows(GetPersons());

        writer.Flush();
        writer.Close();
    }

    private static IEnumerable<Person> GetPersons()
    {
        yield return new Person
            {
                FirstName = "Jhon", 
                LastName = "Doe", 
                Sex = 'M'
            };

        yield return new Person
            {
                FirstName = "Jhane", 
                LastName = "Doe",
                Sex = 'F',
                BirthDate = DateTime.Now
            };
        }
    }


    class Person
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public char Sex  { get; set; }

        public DateTime BirthDate { get; set; }
    }

Easy way of running the same junit test over and over?

I've found that Spring's repeat annotation is useful for that kind of thing:

@Repeat(value = 10)

Latest (Spring Framework 4.3.11.RELEASE API) doc:

How do I loop through rows with a data reader in C#?

There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        string value1 = rdr.GetString(0);
        string value2 = rdr.GetString(1);
        string value3 = rdr.GetString(2);
    }
}

What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....

Mutex example / tutorial?

The best threads tutorial I know of is here:

https://computing.llnl.gov/tutorials/pthreads/

I like that it's written about the API, rather than about a particular implementation, and it gives some nice simple examples to help you understand synchronization.

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

Does Python have a package/module management system?

I don't see either MacPorts or Homebrew mentioned in other answers here, but since I do see them mentioned elsewhere on Stack Overflow for related questions, I'll add my own US$0.02 that many folks seem to consider MacPorts as not only a package manager for packages in general (as of today they list 16311 packages/ports, 2931 matching "python", albeit only for Macs), but also as a decent (maybe better) package manager for Python packages/modules:

Question

"...what is the method that Mac python developers use to manage their modules?"

Answers

SciPy

"Macs (unlike Linux) don’t come with a package manager, but there are a couple of popular package managers you can install. Macports..."

I'm still debating on whether or not to use MacPorts myself, but at the moment I'm leaning in that direction.

Get distance between two points in canvas

Note that Math.hypot is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.

So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1).

HTML "overlay" which allows clicks to fall through to elements behind it

A silly hack I did was to set the height of the element to zero but overflow:visible; combining this with pointer-events:none; seems to cover all the bases.

.overlay {
    height:0px;
    overflow:visible;
    pointer-events:none;
    background:none !important;
}

Swift_TransportException Connection could not be established with host smtp.gmail.com

firstly,check for gmail SMTP server . you should have to allow access for less secured apps without allowing swift mailer is not possible.for this login in your email account first then go into privacy settings and then click on sign and security then click on apps without access and then make on to less secure apps option then try mailer again, it will work then.

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

Using Node.js require vs. ES6 import/export

As of right now ES6 import, export is always compiled to CommonJS, so there is no benefit using one or other. Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file.

ES6 → import, export default, export

CommonJS → require, module.exports, exports.foo

Below is common usage of those.

ES6 export default

// hello.js
function hello() {
  return 'hello'
}
export default hello

// app.js
import hello from './hello'
hello() // returns hello

ES6 export multiple and import multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
export { hello1, hello2 }

// app.js
import { hello1, hello2 } from './hello'
hello1()  // returns hello1
hello2()  // returns hello2

CommonJS module.exports

// hello.js
function hello() {
  return 'hello'
}
module.exports = hello

// app.js
const hello = require('./hello')
hello()   // returns hello

CommonJS module.exports multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
module.exports = {
  hello1,
  hello2
}

// app.js
const hello = require('./hello')
hello.hello1()   // returns hello1
hello.hello2()   // returns hello2

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

How to compare two double values in Java?

        int mid = 10;
        for (double j = 2 * mid; j >= 0; j = j - 0.1) {
            if (j == mid) {
                System.out.println("Never happens"); // is NOT printed
            }

            if (Double.compare(j, mid) == 0) {
                System.out.println("No way!"); // is NOT printed
            }

            if (Math.abs(j - mid) < 1e-6) {
                System.out.println("Ha!"); // printed
            }
        }
        System.out.println("Gotcha!");

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

Unicode characters in URLs

Depending on your URL scheme, you can make the UTF-8 encoded part "not important". For example, if you look at Stack Overflow URLs, they're of the following form:

http://stackoverflow.com/questions/2742852/unicode-characters-in-urls

However, the server doesn't actually care if you get the part after the identifier wrong, so this also works:

http://stackoverflow.com/questions/2742852/?????????????????

So if you had a layout like this, then you could potentially use UTF-8 in the part after the identifier and it wouldn't really matter if it got garbled. Of course this probably only works in somewhat specialised circumstances...

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

What exactly is an instance in Java?

The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.

Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.

   class A
    {
    int x=0;
    public static void main(String [] args)    
     {
    int y=0;
    y=y+1;
    x=x+1;
     }   

    }

Let us compile and run this code.

step 1: javac A.class (.class file is generated which is byte code)

step 2: java A (.class file is converted into executable code)

During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).

So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.

This is done through creating the Object and the keyword NEW does this Job.

"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "

The Object is also called the instance of the class.

How to install node.js as windows service?

https://nssm.cc/ service helper good for create windows service by batch file i use from nssm & good working for any app & any file

What is the purpose of Android's <merge> tag in XML layouts?

<merge/> is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.

For example, if you were to <include/> a layout from another file without using merge, the two files might look something like this:

layout1.xml:

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

which is functionally equivalent to this single layout:

<FrameLayout>
   <FrameLayout>
      <TextView />
      <TextView />
   </FrameLayout>
</FrameLayout>

That FrameLayout in layout2.xml may not be useful. <merge/> helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):

layout2.xml:

<merge>
   <TextView />
   <TextView />
</merge>

This is functionally equivalent to this layout:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

but since you are using <include/> you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

html div onclick event

Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.

<div class="expandable-panel-heading">
<h2>
  <a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>

http://jsfiddle.net/NXML7/1/

Is the ternary operator faster than an "if" condition in Java

Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

How to make an ImageView with rounded corners?

None of the methods provided in the answers worked for me. I found the following way works if your android version is 5.0 or above:

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

                    ViewOutlineProvider provider = new ViewOutlineProvider() {
                        @Override
                        public void getOutline(View view, Outline outline) {
                            int curveRadius = 24;
                            outline.setRoundRect(0, 0, view.getWidth(), (view.getHeight()+curveRadius), curveRadius);
                        }
                    };
                    imageview.setOutlineProvider(provider);
                    imageview.setClipToOutline(true);
        }   

No xml shapes to be defined, and the code above create corners only for top, which normal methods won't work. If you need 4 corners to be rounded, remove:

"+ curveRadius"  

From the parameter for bottom in setRoundRect. You can further expand the shape to any others by specifying outlines that suit your needs. Check out the following link:

Android Developer Documentation.

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

How can I format decimal property to currency?

A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

EF LINQ include multiple and nested entities

In Entity Framework Core (EF.core) you can use .ThenInclude for including next levels.

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .ToList();

More information: https://docs.microsoft.com/en-us/ef/core/querying/related-data

Note: Say you need multiple ThenInclude() on blog.Posts, just repeat the Include(blog => blog.Posts) and do another ThenInclude(post => post.Other).

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Other)
 .ToList();

How do I trim whitespace?

If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.

EXAMPLE:

txt="potatoes"
print("I love ",txt,"",sep="")

This will print: I love potatoes.

Instead of: I love potatoes .

In your case, since you would be trying to get ride of the \t, do sep="\t"

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

How do you update Xcode on OSX to the latest version?

I ran into this bugger too.

I was running an older version of Xcode (not compatible with ios 9.2) so I needed to update.

I spent hours on this and was constantly getting spinning wheel of death in the app store. Nothing worked. I tried CLI softwareupdate, updating OSX, everything.

I ultimately had to download AppZapper, then nuked XCode.

I went into the app store to download and it still didn't work. Then I rebooted.

And from here I could finally upgrade to a fresh version of xcode.

WARNING: AppZapper can delete all your data around Xcode as well, so be prepared to start from scratch on your profiles, keys, etc. Also per the other notes here, of course be ready for a 3-5 hour long downloading expedition...

How to tell which disk Windows Used to Boot

There is no boot.ini on a machine with just Vista installed.

How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).

For the simple case check out GetSystemDirectory

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Python 3.1.1 string to hex

binascii methodes are easier by the way

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'

Hope it helps. :)

How do I use an image as a submit button?

<form id='formName' name='formName' onsubmit='redirect();return false;'>
        <div class="style7">
    <input type='text' id='userInput' name='userInput' value=''>
    <img src="BUTTON1.JPG" onclick="document.forms['formName'].submit();">
</div>
</form>

Show Error on the tip of the Edit Text Android

u can use this :

@Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
                Bank bank = BankUtil.findByPan(s.toString());
                if (null != bank && mNewPanEntered && !mNameDefined) {
                    mNewPanEntered = false;
                    suggestCardName(bank);
                }

private void suggestCardName(Bank bank) {
    mLastSuggestTime = System.currentTimeMillis();
    if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
        inputCardNumber.setError(R.string.balance_not_enmb, true);

    }
}

How to install VS2015 Community Edition offline

For the latest VS2015 sp3, the command line shoud be:

en_visual_studio_community_2015_with_update_3_x86_x64_web_installer_8922963.exe /Layout c:\VS2015sp3_offline

How to zero pad a sequence of integers in bash so that all have the same width?

Other way :

zeroos="000"
echo 

for num in {99..105};do
 echo ${zeroos:${#num}:${#zeroos}}${num}
done

So simple function to convert any number would be:

function leading_zero(){

    local num=$1
    local zeroos=00000
    echo ${zeroos:${#num}:${#zeroos}}${num} 

}

How can I delete a user in linux when the system says its currently used in a process

Only solution that worked for me

$ sudo killall -u username && sudo deluser --remove-home -f username

The killall command is used if multiple processes are used by the user you want to delete.

The -f option forces the removal of the user account, even if the user is still logged in. It also forces deluser to remove the user's home directory and mail spool, even if another user uses the same home directory.

Please confirm that it works in the comments.

How to switch databases in psql?

Using psql's meta-command \c or \connect [ dbname [ username ] [ host ] [ port ] ] | conninfo (see documentation).

Example: \c MyDatabase

Note that the \c and \connect meta-commands are case-sensitive.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")
         document.getElementById("test").style.color="black";
    else
         document.getElementById("test").style.color="red";
}

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

How to enumerate a range of numbers starting at 1

Easy, just define your own function that does what you want:

def enum(seq, start=0):
    for i, x in enumerate(seq):
        yield i+start, x

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Search in all files in a project in Sublime Text 3

Solution:

Use the Search all shortcut: Ctrl+Shift+F, then select the folder in the "Where:" box below. (And for Mac, it's ?+Shift+F).

If the root directory for the project is proj, with subdirectories src and aux and you want to search in all subfolders, use the proj folder. To restrict the search to only the src folder, use proj/src in the "Where: " box.

Create stacked barplot where each stack is scaled to sum to 100%

You just need to divide each element by the sum of the values in its column.

Doing this should suffice:

data.perc <- apply(data, 2, function(x){x/sum(x)})

Note that the second parameter tells apply to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

How can I set a UITableView to grouped style

If you have one TableView for more tables, and one of this tables is grouped and the another one plain, than you can simulate the plain style with the function from UITableViewDelegate:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {   
    return CGFloat.min
}

Switching between GCC and Clang/LLVM using CMake

System wide C change on Ubuntu:

sudo update-alternatives --config cc

System wide C++ change on Ubuntu:

sudo update-alternatives --config c++

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

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

How do I remove all non-ASCII characters with regex and Notepad++?

In addition to the answer by ProGM, in case you see characters in boxes like NUL or ACK and want to get rid of them, those are ASCII control characters (0 to 31), you can find them with the following expression and remove them:

[\x00-\x1F]+

In order to remove all non-ASCII AND ASCII control characters, you should remove all characters matching this regex:

[^\x1F-\x7F]+

Could not find folder 'tools' inside SDK

I faced similar issue when the SDK tools installation was failed during the initial setup. To resolution is to download SDK tools from Android Developer Site

  • Expand "USE AN EXISTING IDE" section and download standalone SDK tools
  • Choose your destination as (%HOMEPATH%\android-sdks)
  • Now start Android-SDKs folder and run SDK manager

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

How to convert jsonString to JSONObject in Java

Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:

(1) Convert JSON String to Java bean

public static String beanToJSONString(Object myJavaBean) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.writeValueAsString(myJavaBean);
}

(2) Convert JSON String to JSON object (JsonNode)

public static JsonNode stringToJSONObject(String jsonString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readTree(jsonString);
}

//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";   
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());

(3) Convert Java bean to JSON String

    public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readValue(JSONString, beanClass);
}

REFS:

  1. Codehaus Jackson

  2. JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object

  3. Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode

How to read file using NPOI

private DataTable GetDataTableFromExcel(String Path)
    {
        XSSFWorkbook wb;
        XSSFSheet sh;
        String Sheet_name;

        using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
        {
            wb = new XSSFWorkbook(fs);

               Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
        }
        DataTable DT = new DataTable();
        DT.Rows.Clear();
        DT.Columns.Clear();

        // get sheet
        sh = (XSSFSheet)wb.GetSheet(Sheet_name);

        int i = 0;
        while (sh.GetRow(i) != null)
        {
            // add neccessary columns
            if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
            {
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                {
                    DT.Columns.Add("", typeof(string));
                }
            }

            // add row
            DT.Rows.Add();

            // write row value
            for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
            {
                var cell = sh.GetRow(i).GetCell(j);

                if (cell != null)
                {
                    // TODO: you can add more cell types capatibility, e. g. formula
                    switch (cell.CellType)
                    {
                        case NPOI.SS.UserModel.CellType.Numeric:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                            //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;

                            break;
                        case NPOI.SS.UserModel.CellType.String:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;

                            break;
                    }
                }
            }

            i++;
        }

        return DT;
    }

How to get longitude and latitude of any address?

I came up with the following which takes account of rubbish passed in and file_get_contents failing....

function get_lonlat(  $addr  ) {
    try {
            $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
            $e=json_decode($coordinates);
            // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
            if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
            // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
            if ( $coordinates == false   ||  $err_res ==  true  ) {
                $a = array( 'lat'=>0,'lng'=>0);
                $coordinates  = new stdClass();
                foreach (  $a  as $key => $value)
                {
                    $coordinates->$key = $value;
                }
            } else {
                // call to google ok so just return longitude/latitude.
                $coordinates = $e;

                $coordinates  =  $coordinates->results[0]->geometry->location;
            }

            return $coordinates;
    }
    catch (Exception $e) {
    }

then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

How do I set a VB.Net ComboBox default value

You can try this:

Me.cbo1.Text = Me.Cbo1.Items(0).Tostring

clientHeight/clientWidth returning different values on different browsers

Paul A is right about why the discrepancy exists but the solution offered by Ngm is wrong (in the sense of JQuery).

The equivalent of clientHeight and clientWidth in jquery (1.3) is

$(window).width(), $(window).height()

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Try putting the following class on your second button

.div-button
{
    margin-left: 20px;
}

Edit:

If you want your first button to be spaced from the div as well as from the second button, then apply this class to your first button also.

Capture key press (or keydown) event on DIV element

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

Command not found after npm install in zsh

For Mac users:

Alongside the following: nvm, iterm2, zsh

I found using the .bashrc rather than .profile or .bash_profile caused far less issues.

Simply by adding the latter to my .zshrc file:

source $HOME/.bashrc

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

CodeIgniter : Unable to load the requested file:

File names are case sensitive - please check your file name. it should be in same case in view folder

How do I Convert DateTime.now to UTC in Ruby?

Try this, works in Ruby:

DateTime.now.to_time.utc

java.lang.RuntimeException: Unable to start activity ComponentInfo

It was my own stupidity:

java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());

Putting this inside onCreate() method fixed my problem.

How do I mock an autowired @Value field in Spring with Mockito?

I used the below code and it worked for me:

@InjectMocks
private ClassABC classABC;

@Before
public void setUp() {
    ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}

Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/

How to program a fractal?

Well, simple and graphically appealing don't really go hand in hand. If you're serious about programming fractals, I suggest reading up on iterated function systems and the advances that have been made in rendering them.

http://flam3.com/flame_draves.pdf

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

Base64 encoding and decoding in client-side Javascript

Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xff fix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

How to include "zero" / "0" results in COUNT aggregate?

if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)

Ex:

select P.person_id, nvl(A.nb_apptmts, 0) from 
(SELECT person.person_id
FROM person) P
LEFT JOIN 
(select person_id, count(*) as nb_apptmts
from appointment 
group by person_id) A
ON P.person_id = A.person_id

PHP DOMDocument loadHTML not encoding UTF-8 correctly

This took me a while to figure out but here's my answer.

Before using DomDocument I would use file_get_contents to retrieve urls and then process them with string functions. Perhaps not the best way but quick. After being convinced Dom was just as quick I first tried the following:

$dom = new DomDocument('1.0', 'UTF-8');
if ($dom->loadHTMLFile($url) == false) { // read the url
    // error message
}
else {
    // process
}

This failed spectacularly in preserving UTF-8 encoding despite the proper meta tags, php settings and all the rest of the remedies offered here and elsewhere. Here's what works:

$dom = new DomDocument('1.0', 'UTF-8');
$str = file_get_contents($url);
if ($dom->loadHTML(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8')) == false) {
}

etc. Now everything's right with the world. Hope this helps.

Commenting in a Bash script inside a multiline command

Here is a bash script that combines the ideas and idioms of several previous comments to provide, with examples, inline comments having the general form ${__+ <comment text>}.

In particular

  • <comment text> can be multi-line
  • <comment text> is not parameter-expanded
  • no subprocesses are spawned (so comments are efficient)

There is one restriction on the <comment text>, namely, unbalanced braces '}' and parentheses ')' must be protected (i.e., '\}' and '\)').

There is one requirement on the local bash environment:

  • the parameter name __ must be unset

Any other syntactically valid bash parameter-name will serve in place of __, provided that the name has no set value.

An example script follows

# provide bash inline comments having the form
#     <code> ${__+ <comment>} <code> 
#     <code> ${__+ <multiline
#                   comment>} <code>

# utility routines that obviate "useless use of cat"
function bashcat { printf '%s\n' "$(</dev/stdin)"; }
function scat { 1>&2 bashcat; exit 1; }

# ensure that '__' is unset && remains unset
[[ -z ${__+x} ]] &&  # if '__' is unset
  declare -r __ ||   # then ensure that '__' remains unset 
  scat <<EOF         # else exit with an error
Error: the parameter __='${__}' is set, hence the
  comment-idiom '\${__+ <comment text>}' will fail
EOF

${__+ (example of inline comments)
------------------------------------------------
the following inline comment-idiom is supported
    <code> ${__+ <comment>} <code> 
    <code> ${__+ <multiline
                  comment>} <code> 
(advisory) the parameter '__' must NOT be set;
  even the null declaration __='' will fail
(advisory) protect unbalanced delimiters \} and \) 
(advisory) NO parameter-expansion of <comment> 
(advisory) NO subprocesses are spawned
(advisory) a functionally equivalent idiom is 
    <code> `# <comment>` <code> 
    <code> `# <multiline
               comment>` <code>
however each comment spawns a bash subprocess
that inelegantly requires ~1ms of computation 
------------------------------------------------}

How do I delete an exported environment variable?

this may also work.

export GNUPLOT_DRIVER_DIR=

Copy rows from one table to another, ignoring duplicates

Have you try first remove duplicates in the subquery?

INSERT INTO destTable
SELECT source.* FROM(
    SELECT *
    FROM srcTable
    EXCEPT
    SELECT src.* FROM
    srcTable AS src
    INNER JOIN destTable AS dest 
    /* put in below line the conditions to match repeated registers */
        ON dest.SOME_FANCY_MATCH = src.SOME_FANCY_MATCH AND ... 
) as source

If the sets are very large, maybe this is not the best solution.

How do you read CSS rule values with JavaScript?

Based on @dude answer this should return relevant styles in a object, for instance:

.recurly-input {                                                                                                                                                                             
  display: block;                                                                                                                                                                            
  border-radius: 2px;                                                                                                                                                                        
  -webkit-border-radius: 2px;                                                                                                                                                                
  outline: 0;                                                                                                                                                                                
  box-shadow: none;                                                                                                                                                                          
  border: 1px solid #beb7b3;                                                                                                                                                                 
  padding: 0.6em;                                                                                                                                                                            
  background-color: #f7f7f7;                                                                                                                                                                 
  width:100%;                                                                                                                                                                                
}

This will return:

backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"

Code:

function getStyle(className_) {

    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        if (!classes)
            continue;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
            }
        }
    }

}

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

underscore.js is using the following

toString = Object.prototype.toString;

_.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

_.isObject = function(obj) {
    return obj === Object(obj);
  };

_.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

Unresolved reference issue in PyCharm

After following the accepted answer, doing the following solved it for me:

File ? Settings ? Project <your directory/project> ? Project Dependencies

Chose the directory/project where your file that has unresolved imports resides and check the box to tell Pycharm that that project depends on your other project.

My folder hierarcy is slightly different from the one in the question. Mine is like this

+-- MyDirectory  
¦     +-- simulate.py  
+-- src  
¦     +-- networkAlgorithm.py  
¦     +-- ...

Telling Pycharm that src depends on MyDirectory solved the issue for me!

Returning a value from thread?

Here is a simple example using a delegate ...

void Main()
{
   DoIt d1 = Doer.DoThatThang;
   DoIt d2 = Doer.DoThatThang;

   IAsyncResult r1 = d1.BeginInvoke( 5, null, null );
   IAsyncResult r2 = d2.BeginInvoke( 10, null, null );

   Thread.Sleep( 1000 );

   var s1 = d1.EndInvoke( r1 );
   var s2 = d2.EndInvoke( r2 );

   s1.Dump(); // You told me 5
   s2.Dump(); // You told me 10
}

public delegate string DoIt( int x );

public class Doer
{
  public static string DoThatThang( int x  )
  {
    return "You told me " + x.ToString();
  }
}

There's a terrific series on threading at Threading in C#.

Java - JPA - @Version annotation

Just adding a little more info.

JPA manages the version under the hood for you, however it doesn't do so when you update your record via JPAUpdateClause, in such cases you need to manually add the version increment to the query.

Same can be said about updating via JPQL, i.e. not a simple change to the entity, but an update command to the database even if that is done by hibernate

Pedro