Programs & Examples On #Ocamlfind

Resetting a form in Angular 2 after submit

When I was going through the Angular basics guide on forms, and hit the resetting of forms section, I was very much left in surprise when I read the following in regards to the solution they give.

This is a temporary workaround while we await a proper form reset feature.

I personally haven't tested if the workaround they provided works (i assume it does), but I believe it is not neat, and that there must be a better way to go about the issue.

According to the FormGroup API (which is marked as stable) there already is a 'reset' method.

I tried the following. In my template.html file i had

<form (ngSubmit)="register(); registrationForm.reset();" #registrationForm="ngForm">
    ...
</form>

Notice that in the form element, I've initialised a template reference variable 'registrationForm' and initialized it to the ngForm Directive, which "governs the form as a whole". This gave me access to the methods and attributes of the governing FormGroup, including the reset() method.

Binding this method call to the ngSubmit event as show above reset the form (including pristine, dirty, model states etc) after the register() method is completed. For a demo this is ok, however it isn't very helpful for real world applications.

Imagine the register() method performs a call to the server. We want to reset the form when we know that the server responded back that everything is OK. Updating the code to the following caters for this scenario.

In my template.html file :

<form (ngSubmit)="register(registrationForm);" #registrationForm="ngForm">
    ...
</form>

And in my component.ts file :

@Component({
  ...
})
export class RegistrationComponent {
  register(form: FormGroup) {

   ...

   // Somewhere within the asynchronous call resolve function
   form.reset();
  }
}

Passing the 'registrationForm' reference to the method would allow us to call the reset method at the point of execution that we want to.

Hope this helps you in any way. :)

Note: This approach is based on Angular 2.0.0-rc.5

set column width of a gridview in asp.net

Set width

HeaderStyle-width

for Example HeaderStyle-width="10%"

Get index of a key in json

What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.

"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

After upgrading from Ubuntu 14.04 lts to Ubuntu 16.04 lts I found a yet another reason for this error that I haven't seen before.

During the upgrading process I had somehow lost my php5-fpm executable altogether. All the config files were intact and it took me a while to realize that service php5-fpm start didn't really start a process, as it did not show any errors.

My moment of awakening was when I noticed that there were no socket file in /var/run/php5-fpm.sock, as there should be, nor did netstat -an show processes listening on the port that I tried as an alternative while trying to solve this problem. Since the file /usr/sbin/php5-fpm was also non-existing, I was finally on the right track.

In order to solve this problem I upgraded php from version 5.5 to 7.0. apt-get install php-fpm did the trick as a side effect. After that and installing other necessary packages everything was back to normal.


This upgrading solution may have problems of its own, however. Since php has evolved quite a bit, it's possible that the software will break in unimaginable ways. So, even though I did go down that path, you may want to keep the version you're fond of just for a while longer.

Luckily, there seems to be a neat way for that, as described on The Customize Windows site:

add-apt-repository ppa:ondrej/php
apt-get purge php5-common
apt-get update
apt-get install php5.6

Neater solution as it might be, I didn't try that. I expect the next couple of days will tell me whether I should have.

How does the keyword "use" work in PHP and can I import classes with it?

I agree with Green, Symfony needs namespace, so why not use them ?

This is how an example controller class starts:

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WelcomeController extends Controller { ... }

How to determine when Fragment becomes visible in ViewPager

I had the same issue. ViewPager executes other fragment life cycle events and I could not change that behavior. I wrote a simple pager using fragments and available animations. SimplePager

intelliJ IDEA 13 error: please select Android SDK

I have same problem once.I solved this by File->Open->other project,then switch this project by this way.

Generate a random point within a circle (uniformly)

I used once this method: This may be totally unoptimized (ie it uses an array of point so its unusable for big circles) but gives random distribution enough. You could skip the creation of the matrix and draw directly if you wish to. The method is to randomize all points in a rectangle that fall inside the circle.

bool[,] getMatrix(System.Drawing.Rectangle r) {
    bool[,] matrix = new bool[r.Width, r.Height];
    return matrix;
}

void fillMatrix(ref bool[,] matrix, Vector center) {
    double radius = center.X;
    Random r = new Random();
    for (int y = 0; y < matrix.GetLength(0); y++) {
        for (int x = 0; x < matrix.GetLength(1); x++)
        {
            double distance = (center - new Vector(x, y)).Length;
            if (distance < radius) {
                matrix[x, y] = r.NextDouble() > 0.5;
            }
        }
    }

}

private void drawMatrix(Vector centerPoint, double radius, bool[,] matrix) {
    var g = this.CreateGraphics();

    Bitmap pixel = new Bitmap(1,1);
    pixel.SetPixel(0, 0, Color.Black);

    for (int y = 0; y < matrix.GetLength(0); y++)
    {
        for (int x = 0; x < matrix.GetLength(1); x++)
        {
            if (matrix[x, y]) {
                g.DrawImage(pixel, new PointF((float)(centerPoint.X - radius + x), (float)(centerPoint.Y - radius + y)));
            }
        }
    }

    g.Dispose();
}

private void button1_Click(object sender, EventArgs e)
{
    System.Drawing.Rectangle r = new System.Drawing.Rectangle(100,100,200,200);
    double radius = r.Width / 2;
    Vector center = new Vector(r.Left + radius, r.Top + radius);
    Vector normalizedCenter = new Vector(radius, radius);
    bool[,] matrix = getMatrix(r);
    fillMatrix(ref matrix, normalizedCenter);
    drawMatrix(center, radius, matrix);
}

enter image description here

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

Displaying files (e.g. images) stored in Google Drive on a website

Per this blog post, a currently working solution is:

<img src=”https://drive.google.com/uc?id=[imageIdGoesHere]" />

Test here

https://drive.google.com/uc?id=1m-uOoFzHn4oUGlEsDSEfPBbJ2QhBJzlM

This is verified to work as of Aug 8, 2020. No shared folder or login is required. But a publicly shared file is.

Creating and playing a sound in swift

import AVFoundation

var audioPlayer = AVAudioPlayer()

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3")
        audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
        audioPlayer.play()
    }
}

How can I install a previous version of Python 3 in macOS using homebrew?

To solve this with homebrew, you can temporarily backdate homebrew-core and set the HOMEBREW_NO_AUTO_UPDATE variable to hold it in place:

cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python

I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.

You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract command:

brew extract python tap_owner/tap_name --version=3.6.5

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

What are the aspect ratios for all Android phone and tablet devices?

The Sony Tablet P is old, but it can switch between 32:15 and 32:30 for each app in landscape mode, and vice-versa in portrait mode, so that's a minimum range to aim for

Material Design not styling alert dialogs

You can consider this project: https://github.com/fengdai/AlertDialogPro

It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

casting Object array to Integer array error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

How to install PyQt4 on Windows using pip?

You can't use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Why use static_cast<int>(x) instead of (int)x?

It's about how much type-safety you want to impose.

When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


EDIT 2014-02-26

I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

How to add to an NSDictionary

When ever the array is declared, then only we have to add the key-value's in NSDictionary like

NSDictionary *normalDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2",@"Value3",@"Key3",nil];

we cannot add or remove the key values in this NSDictionary

Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];'
[mutableDict setObject:@"Value1" forKey:@"Key1"];
[mutableDict setObject:@"Value2" forKey:@"Key2"];
[mutableDict setObject:@"Value3" forKey:@"Key3"];

for removing the key value we have to use the following code

[mutableDict removeObject:@"Value1" forKey:@"Key1"];

remove script tag from HTML content

Because this question is tagged with I'm going to answer with poor man's solution in this situation:

$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

However, regular expressions are not for parsing HTML/XML, even if you write the perfect expression it will break eventually, it's not worth it, although, in some cases it's useful to quickly fix some markup, and as it is with quick fixes, forget about security. Use regex only on content/markup you trust.

Remember, anything that user inputs should be considered not safe.

Better solution here would be to use DOMDocument which is designed for this. Here is a snippet that demonstrate how easy, clean (compared to regex), (almost) reliable and (nearly) safe is to do the same:

<?php

$html = <<<HTML
...
HTML;

$dom = new DOMDocument();

$dom->loadHTML($html);

$script = $dom->getElementsByTagName('script');

$remove = [];
foreach($script as $item)
{
  $remove[] = $item;
}

foreach ($remove as $item)
{
  $item->parentNode->removeChild($item); 
}

$html = $dom->saveHTML();

I have removed the HTML intentionally because even this can bork.

What is the best way to implement constants in Java?

It is BAD habit and terribly ANNOYING practice to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.

I have not read anything Joshua Bloch, so either

  • he is a terrible programmer
  • or the people so far whom I find quoting him (Joshua is the name of a boy I presume) are simply using his material as religious scripts to justify their software religious indulgences.

As in Bible fundamentalism all the biblical laws can be summed up by

  • Love the Fundamental Identity with all your heart and all your mind
  • Love your neighbour as yourself

and so similarly software engineering fundamentalism can be summed up by

  • devote yourself to the ground-zero fundamentals with all your programming might and mind
  • and devote towards the excellence of your fellow-programmers as you would for yourself.

Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn

  • First love yourself. Because if you don't love yourself much, then the concept "love your neighbour as yourself" doesn't carry much weight, since "how much you love yourself" is the datum line above which you would love others.

Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.

The fundamental laws of software programming

  • laziness is the virtue of a good programmer
  • you are to make your programming life as easy, as lazy and therefore as effective as possible
  • you are to make the consequences and entrails of your programming as easy, as lazy and therefore as effective as possible for your neigbour-programmers who work with you and pick up your programming entrails.

Interface-pattern constants is a bad habit ???

Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?

Just read the wikipedia article on interface-pattern constants (https://en.wikipedia.org/wiki/Constant_interface), and the silly excuses it states against interface-pattern constants.

  • Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.

    • Also - wait a second proponents of micro-functional programming as a means of not needing an IDE. Wait till you read my explanation on data-model normalization.
  • Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion

    • are not aware of, and the need for, data-model normalization
  • Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of

    • not seeing that "constants" must be treated as contract. And interfaces are used for enforcing or projecting compliance to a contract.
  • It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???

    • Why would you want to engage in such pattern of programming as your persistent livelihood? IOW, why devote yourself to such an AMBIVALENT and bad programming habit ?

Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.

It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.

Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to "violate the intention for interfaces". I don't care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.

The Fundamental is Data-Model Normalization

It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.

We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.

Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.

A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.

The Fundamentals of Data Normalization

What EF Codd failed to express.

Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.

  1. The Unity and Identity of data instances.
    • design the granularity of each data component, whereby their granularity is at a level where each instance of a component can be uniquely identified and retrieved.
    • absence of instance aliasing. i.e., no means exist whereby an identification produces more than one instance of a component.
  2. Absence of instance crosstalk. There does not exist the necessity to use one or more other instances of a component to contribute to identifying an instance of a component.
  3. The unity and identity of data components/dimensions.
    • Presence of component de-aliasing. There must exist one definition whereby a component/dimension can be uniquely identified. Which is the primary definition of a component;
    • where the primary definition will not result in exposing sub-dimensions or member-components that are not part of an intended component;
  4. Unique means of component dealiasing. There must exist one, and only one, such component de-aliasing definition for a component.
  5. There exists one, and only one, definition interface or contract to identify a parent component in a hierarchical relationship of components.
  6. Absence of component crosstalk. There does not exist the necessity to use a member of another component to contribute to the definitive identification of a component.
    • In such a parent-child relationship, the identifying definition of a parent must not depend on part of the set of member components of a child. A member component of a parent's identity must be the complete child identity without resorting to referencing any or all of the children of a child.
  7. Preempt bi-modal or multi-modal appearances of a data-model.
    • When there exists two candidate definitions of a component, it is an obvious sign that there exists two different data-models being mixed up as one. That means there is incoherence at the data-model level, or the field level.
    • A field of applications must use one and only one data-model, coherently.
  8. Detect and identify component mutation. Unless you have performed statistical component analysis of huge data, you probably do not see, or see the need to treat, component mutation.
    • A data-model may have its some of its components mutate cyclically or gradually.
    • The mode may be member-rotation or transposition-rotation.
    • Member-rotation mutation could be distinct swapping of child components between components. Or where completely new components would have to be defined.
    • Transpositional mutation would manifest as a dimensional-member mutating into an attribute, vice versa.
    • Each mutation cycle must be identified as a distinct data-modal.
  9. Versionize each mutation. Such that you can pull out a previous version of the data model, when perhaps the need arise to treat an 8 year old mutation of the data model.

In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.

Are we still asking if we could use Interface Constants? Really ?

There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.

From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.

Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.

If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.

Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.

Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??

So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...

public interface CustomerService {
  public interface Label{
    char AssignmentCharacter = ':';
    public interface Address{
      String Street = "Street";
      String Unit= "Unit/Suite";
      String Municipal = "City";
      String County = "County";
      String Provincial = "State";
      String PostalCode = "Zip"
    }

    public interface Person {
      public interface NameParts{
        String Given = "First/Given name"
        String Auxiliary = "Middle initial"
        String Family = "Last name"
      }
    }
  }
}

Now I can reference my apps' contracted labels in a way such as

CustomerService.Label.Address.Street
CustomerService.Label.Person.NameParts.Family

This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.

This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.

Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don't want to have to search for constants and I am too lazy to repeatedly type "private final String".

public class PurchaseRequest {
  private interface Constants{
    String INTERESTINGName = "Interesting Name";
    String OFFICIALLanguage = "Official Language"
    int MAXNames = 9;
  }
}

Perhaps even this:

public interface PurchaseOrderConstants {
  public interface Properties{
    default String InterestingName(){
       return something();
    }
    String OFFICIALLanguage = "Official Language"
    int MAXNames = 9;
  }
}

The only issue with interface constants worth considering is when the interface is implemented.

This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???

After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

Get image data url in JavaScript?

Use onload event to convert image after loading

_x000D_
_x000D_
function loaded(img) {_x000D_
  let c = document.createElement('canvas')_x000D_
  c.getContext('2d').drawImage(img, 0, 0)_x000D_
  msg.innerText= c.toDataURL();_x000D_
}
_x000D_
pre { word-wrap: break-word; width: 500px; white-space: pre-wrap; }
_x000D_
<img onload="loaded(this)" src="https://cors-anywhere.herokuapp.com/http://lorempixel.com/200/140" crossorigin="anonymous"/>_x000D_
_x000D_
<pre id="msg"></pre>
_x000D_
_x000D_
_x000D_

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

jQuery event handlers always execute in order they were bound - any way around this?

You can do a custom namespace of events.

$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});

Then, when you need to trigger them you can choose the order.

$('span').trigger('click.doStuff1').trigger('click.doStuff2');

or

$('span').trigger('click.doStuff2').trigger('click.doStuff1');

Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do

$('span').trigger('click'); 

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

Error running android: Gradle project sync failed. Please fix your project and try again

Go to

file->settings->build,execution,deployment->gradle.

(and set gradle home path from your directory)

how to POST/Submit an Input Checkbox that is disabled?

I've solved that problem.

Since readonly="readonly" tag is not working (I've tried different browsers), you have to use disabled="disabled" instead. But your checkbox's value will not post then...

Here is my solution:

To get "readonly" look and POST checkbox's value in the same time, just add a hidden "input" with the same name and value as your checkbox. You have to keep it next to your checkbox or between the same <form></form> tags:

<input type="checkbox" checked="checked" disabled="disabled" name="Tests" value="4">SOME TEXT</input>

<input type="hidden" id="Tests" name="Tests" value="4" />

Also, just to let ya'll know readonly="readonly", readonly="true", readonly="", or just READONLY will NOT solve this! I've spent few hours to figure it out!

This reference is also NOT relevant (may be not yet, or not anymore, I have no idea): http://www.w3schools.com/tags/att_input_readonly.asp

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Well, its not compulsory to restart the emulator you can also reset adb from eclipse itself.

1.) Go to DDMS and there is a reset adb option, please see the image below. enter image description here

2.) You can restart adb manually from command prompt

  run->cmd->your_android_sdk_path->platform-tools>

Then write the below commands.

adb kill-server - To kill the server forcefully

adb start-server - To start the server

UPDATED:

F:\android-sdk-windows latest\platform-tools>adb kill-server

F:\android-sdk-windows latest\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

React Native: Getting the position of an element

React Native provides a .measure(...) method which takes a callback and calls it with the offsets and width/height of a component:

myComponent.measure( (fx, fy, width, height, px, py) => {

    console.log('Component width is: ' + width)
    console.log('Component height is: ' + height)
    console.log('X offset to frame: ' + fx)
    console.log('Y offset to frame: ' + fy)
    console.log('X offset to page: ' + px)
    console.log('Y offset to page: ' + py)
})

Example...

The following calculates the layout of a custom component after it is rendered:

class MyComponent extends React.Component {
    render() {
        return <View ref={view => { this.myComponent = view; }} />
    }
    componentDidMount() {
        // Print component dimensions to console
        this.myComponent.measure( (fx, fy, width, height, px, py) => {
            console.log('Component width is: ' + width)
            console.log('Component height is: ' + height)
            console.log('X offset to frame: ' + fx)
            console.log('Y offset to frame: ' + fy)
            console.log('X offset to page: ' + px)
            console.log('Y offset to page: ' + py)
        })        
    }
}

Bug notes

  • Note that sometimes the component does not finish rendering before componentDidMount() is called. If you are getting zeros as a result from measure(...), then wrapping it in a setTimeout should solve the problem, i.e.:

    setTimeout( myComponent.measure(...), 0 )
    

How to clone git repository with specific revision/changeset?

Its simple. You just have to set the upstream for the current branch

$ git clone repo
$ git checkout -b newbranch
$ git branch --set-upstream-to=origin/branch newbranch
$ git pull

That's all

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

Is there a Public FTP server to test upload and download?

Tele2 provides ftp://speedtest.tele2.net , you can log in as anonymous and upload anything to test your upload speed. For download testing they provide fixed size files, you can choose which fits best to your test.

You can connect with username of anonymous and any password (e.g. anonymous ). You can upload files to upload folder. You can't create new folder here. Your file is deleted immediately after successful upload.

Found here: http://speedtest.tele2.net/

display data from SQL database into php/ html table

You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.

$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection

In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.

This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

Handle Button click inside a row in RecyclerView

You can check if you have any similar entries first, if you get a collection with size 0, start a new query to save.

OR

more professional and faster way. create a cloud trigger (before save)

check out this answer https://stackoverflow.com/a/35194514/1388852

Java - Convert String to valid URI object

You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery in Apache commons-httpclient project

Like this (see URIUtil):

URIUtil.encodeQuery("http://www.google.com?q=a b")

will become:

http://www.google.com?q=a%20b

You can of course do it yourself, but URI parsing can get pretty messy...

Using the "With Clause" SQL Server 2008

There are two types of WITH clauses:

Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).

;WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

Here is a select statement also using a WITH clause

SELECT * FROM orders WITH (NOLOCK) where order_id = 123

Simple (non-secure) hash function for JavaScript?

// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
    if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
    var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
    for (i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);
        bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
    }
    var chunk_len = Math.ceil(bytes.length / 32);   
    for (i=0; i<bytes.length; i++) {
        j += bytes[i];
        k++;
        if ((k == chunk_len) || (i == bytes.length-1)) {
            a = Math.floor( j / k );
            if (a < 32)
                hash += '0';
            else if (a > 126)
                hash += 'z';
            else
                hash += dict[  Math.floor( (a-32) / 2.76) ];
            j = k = 0;
        }
    }
    return hash;
}

How to submit form on change of dropdown list?

Very easy to use select option submit

<select name="sortby" onchange="this.form.submit()">
       <option value="">Featured</option>
       <option value="asc" >Price: Low to High</option>
        <option value="desc">Price: High to Low</option>                                   
</select>

This code use and enjoy now:

Read More: Go Link

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

Java program to get the current date without timestamp

I was looking for the same solution and the following worked for me.

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.clear(Calendar.HOUR);
    calendar.clear(Calendar.MINUTE);
    calendar.clear(Calendar.SECOND);
    calendar.clear(Calendar.MILLISECOND);

    Date today = calendar.getTime();

Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.

With the above posted solution I get output as

Wed Sep 11 00:00:00 EDT 2013

Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

What is Node.js' Connect, Express and "middleware"?

node.js

Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.

node.js as a web server: express

Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see. Now you are in.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I had a similar problem. The catalina.out logged this log Message

Apr 17, 2013 5:14:46 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart

Check the localhost.log in the tomcat log directory (in the same directory as catalina.out), to see the exception which caused this error.

Create Pandas DataFrame from a string

Split Method

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)

Troubleshooting "Illegal mix of collations" error in mysql

This is generally caused by comparing two strings of incompatible collation or by attempting to select data of different collation into a combined column.

The clause COLLATE allows you to specify the collation used in the query.

For example, the following WHERE clause will always give the error you posted:

WHERE 'A' COLLATE latin1_general_ci = 'A' COLLATE latin1_general_cs

Your solution is to specify a shared collation for the two columns within the query. Here is an example that uses the COLLATE clause:

SELECT * FROM table ORDER BY key COLLATE latin1_general_ci;

Another option is to use the BINARY operator:

BINARY str is the shorthand for CAST(str AS BINARY).

Your solution might look something like this:

SELECT * FROM table WHERE BINARY a = BINARY b;

or,

SELECT * FROM table ORDER BY BINARY a;

How to add an object to an array

Using ES6 notation, you can do something like this:

For appending you can use the spread operator like this:

_x000D_
_x000D_
var arr1 = [1,2,3]_x000D_
var obj = 4_x000D_
var newData = [...arr1, obj] // [1,2,3,4]_x000D_
console.log(newData);
_x000D_
_x000D_
_x000D_

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

error: strcpy was not declared in this scope

When you say:

 #include <cstring>

the g++ compiler should put the <string.h> declarations it itself includes into the std:: AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy with std::strcpy and see if that fixes the problem.

How to set specific Java version to Maven

To avoid any impact to your project and to your Environment Variables, you can configure the Maven Compiler Plugin just to the project's POM, specifying the Source and Target java version

  <plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
        </configuration>
    </plugin>
    ...
  </plugins>

Why am I getting AttributeError: Object has no attribute

I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Convert a Unicode string to an escaped ASCII string

Here is my current implementation:

public static class UnicodeStringExtensions
{
    public static string EncodeNonAsciiCharacters(this string value) {
        var bytes = Encoding.Unicode.GetBytes(value);
        var sb = StringBuilderCache.Acquire(value.Length);
        bool encodedsomething = false;
        for (int i = 0; i < bytes.Length; i += 2) {
            var c = BitConverter.ToUInt16(bytes, i);
            if ((c >= 0x20 && c <= 0x7f) || c == 0x0A || c == 0x0D) {
                sb.Append((char) c);
            } else {
                sb.Append($"\\u{c:x4}");
                encodedsomething = true;
            }
        }
        if (!encodedsomething) {
            StringBuilderCache.Release(sb);
            return value;
        }
        return StringBuilderCache.GetStringAndRelease(sb);
    }


    public static string DecodeEncodedNonAsciiCharacters(this string value)
      => Regex.Replace(value,/*language=regexp*/@"(?:\\u[a-fA-F0-9]{4})+", Decode);

    static readonly string[] Splitsequence = new [] { "\\u" };
    private static string Decode(Match m) {
        var bytes = m.Value.Split(Splitsequence, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => ushort.Parse(s, NumberStyles.HexNumber)).SelectMany(BitConverter.GetBytes).ToArray();
        return Encoding.Unicode.GetString(bytes);
    }
}

This passes a test:

public void TestBigUnicode() {
    var s = "\U00020000";
    var encoded = s.EncodeNonAsciiCharacters();
    var decoded = encoded.DecodeEncodedNonAsciiCharacters();
    Assert.Equals(s, decoded);
}

with the encoded value: "\ud840\udc00"

This implementation makes use of a StringBuilderCache (reference source link)

How to convert any Object to String?

"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.

Declaration: java.lang.Object.toString()

Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.

Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );

You can find the complete code here. You can test the code here.

Concatenating null strings in Java

You are not using the "null" and therefore you don't get the exception. If you want the NullPointer, just do

String s = null;
s = s.toString() + "hello";

And I think what you want to do is:

String s = "";
s = s + "hello";

Using C# to read/write Excel files (.xls/.xlsx)

If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.

There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case I upgraded to VS2017 and wanted to build all projects with MSBuild 4 with my build script (which had been using MSBuild 3.5 when we were using VS2015). That MSBuild upgrade appeared fine for the Windows desktop applications but the ones for Windows CE with compact framework would give me this confusing error. Reverting to MSBuild 3.5 for Windows CE projects fixed the issue for me.

I did have the BOM in .csproj files by the way and removed them for all projects in a solution that would not build but that did not help.

Error: unmappable character for encoding UTF8 during maven compilation

I came across this problem just now and ended up resolving it like so: I opened up the offending .java file in Notepad++ and from the Encoding menu I selected "Convert to UTF-8 without BOM". Saved. Re-ran maven, all went through ok.

If the offending resource was not encoded in UTF-8 - as you have configured for your maven compiler plugin - you would see in the Encoding menu of Np++ a bullet mark next to the file's current encoding (in my case I saw it was set to "Encode in ANSI").

So your maven compiler plugin invoked the Java compiler with the -encoding option set to UTF-8, but the compiler encountered a ANSI-encoded source file and reported this as an error. This used to be a warning previously in Java 5 but is treated as an error in Java 6+

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Javascript swap array elements

With numeric values you can avoid a temporary variable by using bitwise xor

list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];

or an arithmetic sum (noting that this only works if x + y is less than the maximum value for the data type)

list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];

How can I initialize C++ object member variables in the constructor?

Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):

The note is a bit large, so I will demonstrate it here with some sample code.

When you chose to hold the members as I mentioned, you have to keep in mind also these two things:

  1. For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass or MyClass in the original examples and MyClass in the code below), in case there are several (see InnerClass1 in the example below). Meaning, you can "comment out" the m_innerClass1(a) and m_innerClass1(15) only if you enable the InnerClass1 default constructor.

  2. For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2 in the example below).

See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++ version 7.3.0):

#include <iostream>

using namespace std;

class InnerClass1
{
    public:
        InnerClass1(int a) : m_a(a)
        {
            cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
        }

        /* No default constructor
        InnerClass1() : m_a(15)
        {
            cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
        }
        */

        ~InnerClass1()
        {
            cout << "InnerClass1::~InnerClass1" << endl;
        }

    private:
        int m_a;
};

class InnerClass2
{
    public:
        InnerClass2(int a) : m_a(a)
        {
            cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
        }

        InnerClass2() : m_a(15)
        {
            cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
        }

        ~InnerClass2()
        {
            cout << "InnerClass2::~InnerClass2" << endl;
        }

    private:
        int m_a;
};

class MyClass
{
    public:
        MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
        {
            cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
        }

         MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
        {
            cout << "MyClass::MyClass() - m_b:" << m_b << endl;
        }

        ~MyClass()
        {
            cout << "MyClass::~MyClass" << endl;
        }

    private:
        InnerClass1 m_innerClass1;
        InnerClass2 m_innerClass2;
        int m_b;
};

int main(int argc, char** argv)
{
    cout << "main - start" << endl;

    MyClass obj;

    cout << "main - end" << endl;
    return 0;
}

std::vector versus std::array in C++

If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.

Given the following declarations:

int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc;      // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc;    // initialized to [3][5]

A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.

A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.

This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.

This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.

How can I clear the input text after clicking

Using jQuery ...

$('#submitButtonsId').click(
    function(){
        $(#myTextInput).val('');
    });

Using pure Javascript ...

var btn = document.getElementById('submitButton');
btn.onclick = function(){ document.getElementById('myTextInput').value="" };

How would I find the second largest salary from the employee table?

Try this:

SELECT
    salary,
    employeeid
FROM
    employees
ORDER BY
    salary DESC
LIMIT 2

Then just get the second row.

Hadoop "Unable to load native-hadoop library for your platform" warning

I'm not using CentOS. Here is what I have in Ubuntu 16.04.2, hadoop-2.7.3, jdk1.8.0_121. Run start-dfs.sh or stop-dfs.sh successfully w/o error:

# JAVA env
#
export JAVA_HOME=/j01/sys/jdk
export JRE_HOME=/j01/sys/jdk/jre

export PATH=${JAVA_HOME}/bin:${JRE_HOME}/bin:${PATH}:.

# HADOOP env
#
export HADOOP_HOME=/j01/srv/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME

export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

Replace /j01/sys/jdk, /j01/srv/hadoop with your installation path

I also did the following for one time setup on Ubuntu, which eliminates the need to enter passwords for multiple times when running start-dfs.sh:

sudo apt install openssh-server openssh-client
ssh-keygen -t rsa
ssh-copy-id user@localhost

Replace user with your username

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to change value of a request parameter in laravel

If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().

namespace App\Http\Requests\Admin\Category;
    
class CategoryRequest extends AbstractRequest
{
    protected function prepareForValidation()
    {
        if ( ! $this->get('url')) {
            $this->merge([
                'url' => $this->get('name'),
            ]);
        }
        $this->merge([
            'url'    => \Str::slug($this->get('url')),
            'active' => (int)$this->get('active'),
        ]);
    }
}

I hope this information will be useful to somebody.

Perform an action in every sub-directory using Bash

find . -type d -print0 | xargs -0 -n 1 my_command

How to convert a GUID to a string in C#?

String guid = System.Guid.NewGuid().ToString();

Otherwise it's a delegate.

jquery validate check at least one checkbox

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

And on the element:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

In addition, you will likely find the error message display, not quite sufficient. Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid. I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

Hope that helps!

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

// https://github.com/google/guava
import static com.google.common.base.Preconditions.*;

String getDayOfMonthSuffix(final int n) {
    checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);
    if (n >= 11 && n <= 13) {
        return "th";
    }
    switch (n % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}

The table from @kaliatech is nice, but since the same information is repeated, it opens the chance for a bug. Such a bug actually exists in the table for 7tn, 17tn, and 27tn (this bug might get fixed as time goes on because of the fluid nature of StackOverflow, so check the version history on the answer to see the error).

How to make image hover in css?

Hi you should give parent position relative and child absolute and give to height or width to absolute class as like this

Css

  .nkhome{
    margin-left:260px;
    width:59px;
    height:59px;
    margin-top:170px;
    position:relative;
    z-index:0;
}
.nkhome a:hover img{
    opacity:0.0;
}
.nkhome a:hover{
  background:url('http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg');
    width:100px;
    height:100px;
    position:absolute;
    top:0;
    z-index:1;

}

HTML

 <div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" /></a>
    </div>
?

Live demo http://jsfiddle.net/t5FEX/7/


or this

<div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" onmouseover="this.src='http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg'" 
            onmouseout="this.src='http://dummyimage.com/100/000/fff.jpg'"
            /></a>
    </div>?

Live demo http://jsfiddle.net/t5FEX/9/

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

How to search file text for a pattern and replace it with a given value

Another approach is to use inplace editing inside Ruby (not from the command line):

#!/usr/bin/ruby

def inplace_edit(file, bak, &block)
    old_stdout = $stdout
    argf = ARGF.clone

    argf.argv.replace [file]
    argf.inplace_mode = bak
    argf.each_line do |line|
        yield line
    end
    argf.close

    $stdout = old_stdout
end

inplace_edit 'test.txt', '.bak' do |line|
    line = line.gsub(/search1/,"replace1")
    line = line.gsub(/search2/,"replace2")
    print line unless line.match(/something/)
end

If you don't want to create a backup then change '.bak' to ''.

Calling an API from SQL Server stored procedure

The SQL Query select * from openjson ... works only with SQL version 2016 and higher. Need the SQL compatibility mode 130.

MongoDB running but can't connect using shell

I had this problem as well. Is your MongoDB journaling? I noticed the following "preallocate" entries in the log file. Once I saw the last line "waiting for connections on port", I could connect. Notice that this "faster" mode took 12 minutes to intialize.

William

Tue Apr 17 16:48:01 [initandlisten] MongoDB starting : pid=2248 port=27017 dbpath=E:\MongoData 64-bit host=ME
Tue Apr 17 16:48:01 [initandlisten] db version v2.0.0-rc0, pdfile version 4.5
Tue Apr 17 16:48:01 [initandlisten] git version: 8d4bf50111352cee5a4f1abf25b63442d6c45dc4
Tue Apr 17 16:48:01 [initandlisten] build info: windows (6, 1, 7601, 2, 'Service Pack 1') BOOST_LIB_VERSION=1_42
Tue Apr 17 16:48:01 [initandlisten] options: { bind_ip: "ip", dbpath: "E:\MongoData", directoryperdb: true, journal: true, logpath: "E:\MongoData\mongo.log", quiet: true, rest: true, service: true }
Tue Apr 17 16:48:01 [initandlisten] journal dir=E:/MongoData/journal
Tue Apr 17 16:48:01 [initandlisten] recover : no journal files present, no recovery needed
Tue Apr 17 16:48:02 [initandlisten] preallocateIsFaster=true 9.68
Tue Apr 17 16:48:04 [initandlisten] preallocateIsFaster=true 8.44
Tue Apr 17 16:48:06 [initandlisten] preallocateIsFaster=true 9.68
Tue Apr 17 16:48:06 [initandlisten] preallocateIsFaster check took 4.921 secs
Tue Apr 17 16:48:06 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.0
Tue Apr 17 16:52:37 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.1
Tue Apr 17 16:56:54 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.2
Tue Apr 17 17:01:42 [initandlisten] waiting for connections on port 27017
Tue Apr 17 17:01:42 [websvr] admin web console waiting for connections on port 28017

Fatal error: Call to undefined function curl_init()

This is from the official website. php.net

After installation of PHP.

Windows

Move to Windows\system32 folder: libssh2.dll, php_curl.dll, ssleay32.dll, libeay32.dll

Linux

Move to Apache24\bin folder libssh2.dll

Then uncomment extension=php_curl.dll in php.ini

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The docker run command has a --ulimit flag you can use this flag to set the open file limit in your docker container.

Run the following command when spinning up your container to set the open file limit.

docker run --ulimit nofile=<softlimit>:<hardlimit> the first value before the colon indicates the soft file limit and the value after the colon indicates the hard file limit. you can verify this by running your container in interactive mode and executing the following command in your containers shell ulimit -n

PS: check out this blog post for more clarity

Angular.js: set element height on page load

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

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

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};  
            w.bind('resize', function () {        
              changeHeight();   // when window size gets changed             
        });  
        changeHeight(); // when page loads          
    }
})

What does map(&:name) mean in Ruby?

First, &:name is a shortcut for &:name.to_proc, where :name.to_proc returns a Proc (something that is similar, but not identical to a lambda) that when called with an object as (first) argument, calls the name method on that object.

Second, while & in def foo(&block) ... end converts a block passed to foo to a Proc, it does the opposite when applied to a Proc.

Thus, &:name.to_proc is a block that takes an object as argument and calls the name method on it, i. e. { |o| o.name }.

Timestamp to human readable format

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

For example, using it for the current time:

_x000D_
_x000D_
document.write( new Date().toUTCString() );
_x000D_
_x000D_
_x000D_

How to set Status Bar Style in Swift 3

iOS 11.2

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barStyle = .black

    return true
}

What is the equivalent of the C# 'var' keyword in Java?

In general you can use Object class for any type, but you have do type casting later!

eg:-

Object object = 12;
    Object object1 = "Aditya";
    Object object2 = 12.12;

    System.out.println(Integer.parseInt(object.toString()) + 2);

    System.out.println(object1.toString() + " Kumar");
    System.out.println(Double.parseDouble(object2.toString()) + 2.12);

How to get the file extension in PHP?

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Google Colab: how to read data from my google drive?

What I have done is first:

from google.colab import drive
drive.mount('/content/drive/')

Then

%cd /content/drive/My Drive/Colab Notebooks/

After I can for example read csv files with

df = pd.read_csv("data_example.csv")

If you have different locations for the files just add the correct path after My Drive

How to Ping External IP from Java Android

I tried following code, which works for me.

private boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }

Constants in Kotlin -- what's a recommended way to create them?

If you put your const val valName = valValue before the class name, this way it will creates a

public static final YourClass.Kt that will have the public static final values.

Kotlin:

const val MY_CONST0 = 0
const val MY_CONST1 = 1
data class MyClass(var some: String)

Java decompiled:

public final class MyClassKt {
    public static final int MY_CONST0 = 0;
    public static final int MY_CONST1 = 1;
}
// rest of MyClass.java

Revert to Eclipse default settings

None of the answers above worked for me for Mars, so I took drastic measures.

  • Possibly optional: Donwload newest version of Eclipse from their website
  • Possibly optional: Find where your executable of current Eclipse's at, and remove the whole folder (you can't uninstall Eclipse through Configurations because it never really installs itself on the system)
  • Remove the .metadata folder inside your workspace folder, e.g. C:/Users/bram/Documents/workspace/.metadata (you can leave the projects as they were)
  • Remove the .eclipse folder inside {User}, e.g. C:/Users/bram/.eclipse
  • Optional: clean file system (and registry?) with a tool such as CCleaner

The last step is definitely optional, but I'm not sure about the first two. In other words, I can't confirm that the corrupted files were inside eclipse's executable folder, inside .eclipse or inside the workspace's .metadata. I'm pretty sure .metadata isn't the culprit since I'd already removed that before so my guess is that the folder .eclipse in {User} is the cause!

If you've tried my steps, please comment whether or not they helped you and which removed folder you think solved it.

Anaconda Navigator won't launch (windows 10)

I was working on my Windows 10 machine and I'm not sure which package "broke" Spyder and Anaconda Navigator, but could have been either, or, or both Kivy-1.10.1 and moviepy-0.2.3.5 which gave me problems. I installed with either pip or conda. So of course I looked on this site to see what to do to fix. I found how pyqt was probably the issue. I uninstalled pyqt, kivy, and moviepy by using "pip uninstall ". I found where/or how they were installed by "pip list" and "conda list". After they were uninstalled I used "conda install - c anaconda pyqt" to reinstall pyqt. After installing pyqt I launched Spyder with no problems.

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are only 3 joins:

  • A) Cross Join = Cartesian (E.g: Table A, Table B)
  • B) Inner Join = JOIN (E.g: Table A Join/Inner Join Table B)
  • C) Outer join:

       There are three type of outer join
       1)  Left Outer Join     = Left Join
       2)  Right Outer Join    = Right Join
       3)  Full Outer Join     = Full Join    
    

Hope it'd help.

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

You can use a single line to add and remove class on a div. Please remove a class first to add a new class.

$('div').on('click',function(){
  $('div').removeClass('active').addClass('active');     
});

How to split an integer into an array of digits?

like @nd says but using the built-in function of int to convert to a different base

>>> [ int(i,16) for i in '0123456789ABCDEF' ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> [int(i,2) for i in "100 010 110 111".split()]
[4, 2, 6, 7]

I don't know what is the final objective but take a look also inside the decimal module of python for doing stuff like

>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

close vs shutdown socket?

This is explained in Beej's networking guide. shutdown is a flexible way to block communication in one or both directions. When the second parameter is SHUT_RDWR, it will block both sending and receiving (like close). However, close is the way to actually destroy a socket.

With shutdown, you will still be able to receive pending data the peer already sent (thanks to Joey Adams for noting this).

Android Text over image

The below code this will help you

public class TextProperty {
    private int heigt;                              //???????
    private String []context = new String[1024];    //???????

    /*
     *@parameter wordNum
     *
     */
    public TextProperty(int wordNum ,InputStreamReader in) throws Exception {
        int i=0;
        BufferedReader br = new BufferedReader(in);
        String s;
        while((s=br.readLine())!=null){
            if(s.length()>wordNum){
                int k=0;
                while(k+wordNum<=s.length()){
                    context[i++] = s.substring(k, k+wordNum);
                    k=k+wordNum;
                }
                context[i++] = s.substring(k,s.length());
            }
            else{
                context[i++]=s;
            }
        }
        this.heigt = i;
        in.close();
        br.close();
    }


    public int getHeigt() {
        return heigt;
    }

    public String[] getContext() {

        return context;
    }
}
public class MainActivity extends AppCompatActivity {

    private Button btn;
    private ImageView iv;
    private final int WORDNUM = 35;  //??????  ???????
    private final int WIDTH = 450;   //???????

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

        iv = (ImageView) findViewById(R.id.imageView);
        btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int x=5,y=10;
                try {
                    TextProperty tp = new TextProperty(WORDNUM, new InputStreamReader(getResources().getAssets().open("1.txt")));
                    Bitmap bitmap = Bitmap.createBitmap(WIDTH, 20*tp.getHeigt(), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint();
                    paint.setColor(Color.WHITE);
                    paint.setTextAlign(Paint.Align.LEFT);
                    paint.setTextSize(20f);

                    String [] ss = tp.getContext();
                    for(int i=0;i<tp.getHeigt();i++){
                        canvas.drawText(ss[i], x, y, paint);
                        y=y+20;
                    }

                    canvas.save(Canvas.ALL_SAVE_FLAG);
                    canvas.restore();
                    String path = Environment.getExternalStorageDirectory() + "/image.png";
                    System.out.println(path);
                    FileOutputStream os = new FileOutputStream(new File(path));
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                    //Display the image on ImageView.
                    iv.setImageBitmap(bitmap);
                    iv.setBackgroundColor(Color.BLUE);
                    os.flush();
                    os.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}```

One liner for If string is not null or empty else

You can achieve this with pattern matching with the switch expression in C#8/9

FooTextBox.Text = strFoo switch
{
    { Length: >0 } s => s, // If the length of the string is greater than 0 
    _ => "0" // Anything else
};

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

.NET - Get protocol, host, and port

Very similar to Holger's answer. If you need to grab the URL can do something like:

Uri uri = Context.Request.Url;         
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number

The Uri class provides a whole range of methods, many which I have not listed.

In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:

var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

Which successfully grabbed: http://localhost:12345

Setting Icon for wpf application (VS 08)

After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:

  1. Put the icon in a folder <icon_path> in the project directory
  2. Mimic the folder path <icon_path> in the solution
  3. Add a new item (your icon) in the solution folder you created
  4. Add the following code in the WPF window's code behind:

Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));

Please inform me if you have any difficulties implementing this solution so I can help.

JSON character encoding

finally I got the solution:

Only put this line

@RequestMapping(value = "/YOUR_URL_Name",method = RequestMethod.POST,produces = "application/json; charset=utf-8")

this will definitely help.

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

Concatenate text files with Windows command line, dropping leading lines

The help for copy explains that wildcards can be used to concatenate multiple files into one.

For example, to copy all .txt files in the current folder that start with "abc" into a single file named xyz.txt:

copy abc*.txt xyz.txt

Where is the WPF Numeric UpDown control?

This is example of my own UserControl with Up and Down key catching.

Xaml code:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="13" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="13" />
        <RowDefinition Height="13" />
    </Grid.RowDefinitions>
    <TextBox Name="NUDTextBox"  Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" TextAlignment="Right" PreviewKeyDown="NUDTextBox_PreviewKeyDown" PreviewKeyUp="NUDTextBox_PreviewKeyUp" TextChanged="NUDTextBox_TextChanged"/>
    <RepeatButton Name="NUDButtonUP"  Grid.Column="1" Grid.Row="0" FontSize="8" FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="NUDButtonUP_Click">5</RepeatButton>
    <RepeatButton Name="NUDButtonDown"  Grid.Column="1" Grid.Row="1" FontSize="8"  FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="13" VerticalAlignment="Bottom" Click="NUDButtonDown_Click">6</RepeatButton>
</Grid>

And the code:

public partial class NumericUpDown : UserControl
{
    int minvalue = 0, 
        maxvalue = 100,
        startvalue = 10;
    public NumericUpDown()
    {
        InitializeComponent();
        NUDTextBox.Text = startvalue.ToString();
    }

    private void NUDButtonUP_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number < maxvalue)
            NUDTextBox.Text = Convert.ToString(number + 1); 
    }

    private void NUDButtonDown_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number > minvalue)
            NUDTextBox.Text = Convert.ToString(number - 1); 
    }

    private void NUDTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Up)
        {
            NUDButtonUP.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { true }); 
        }


        if (e.Key == Key.Down)
        {
            NUDButtonDown.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { true }); 
        }
    }

    private void NUDTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Up)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { false });

        if (e.Key == Key.Down)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { false });
    }

    private void NUDTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        int number = 0;
        if (NUDTextBox.Text!="")
            if (!int.TryParse(NUDTextBox.Text, out number)) NUDTextBox.Text = startvalue.ToString();
        if (number > maxvalue)  NUDTextBox.Text = maxvalue.ToString();
        if (number < minvalue) NUDTextBox.Text = minvalue.ToString();
        NUDTextBox.SelectionStart = NUDTextBox.Text.Length;

    }

}

How to check if an array value exists?

Well, first off an associative array can only have a key defined once, so this array would never exist. Otherwise, just use in_array() to determine if that specific array element is in an array of possible solutions.

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

How can I read a text file in Android?

Try this

try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

Iterate through object properties

Dominik's answer is perfect, I just prefer to do it that way, as it's cleaner to read:

for (var property in obj) {
    if (!obj.hasOwnProperty(property)) continue;

    // Do stuff...
}

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

Lombok is not generating getter and setter

Download Lombok Jar File https://projectlombok.org/downloads/lombok.jar

Add maven dependency:

   <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.18</version>
   </dependency>   

Start Lombok Installation java -jar lombok-1.16.18.jar

find complete example in this link:
https://howtodoinjava.com/automation/lombok-eclipse-installation-examples/

Find the least number of coins required that can make any change from 1 to 99 cents

Here's a simple version in Python.

#!/usr/bin/env python

required = []
coins = [25, 10, 5, 1]

t = []
for i in range(1, 100):
    while sum(t) != i:
        for c in coins:
            if sum(t) + c <= i:
                t.append(c)
                break
    for c in coins:
        while t.count(c) > required.count(c):
            required.append(c)
    del t[:]

print required

When run, it prints the following to stdout.

[1, 1, 1, 1, 5, 10, 10, 25, 25, 25]

The code is pretty self-explanatory (thanks Python!), but basically the algorithm is to add the largest coin available that doesn't put you over the current total you're shooting for into your temporary list of coins (t in this case). Once you find the most efficient set of coins for a particular total, make sure there are at least that many of each coin in the required list. Do that for every total from 1 to 99 cents, and you're done.

Android : change button text and background color

I think doing this way is much simpler:

button.setBackgroundColor(Color.BLACK);

And you need to import android.graphics.Color; not: import android.R.color;

Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000 where the first byte is setting the alpha.

How to access the request body when POSTing using Node.js and Express?

This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body

var express = require('express');
var app = express.createServer(express.logger());

app.post('/', function(request, response) {

    // push the data to body
    var body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      // on end of data, perform necessary action
      body = Buffer.concat(body).toString();
      response.write(request.body.user);
      response.end();
    });
});

How can I make the cursor turn to the wait cursor?

Use this with WPF:

Cursor = Cursors.Wait;

// Your Heavy work here

Cursor = Cursors.Arrow;

How do you return the column names of a table?

The following seems to be like the first suggested query above but sometime you have to specify the database to get it to work. Note that the query should also work without specifying the TABLE_SCHEMA:

SELECT COLUMN_NAME
FROM   YOUR_DB_NAME.INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_NAME = 'YOUR_TABLE_NAME' AND TABLE_SCHEMA = 'YOUR_DB_NAME'

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

$.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });

Pass by pointer & Pass by reference

Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.

The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.

References can't be updated once they're set, so use a pointer if you ever need to reassign it.

Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.

What does CultureInfo.InvariantCulture mean?

When numbers, dates and times are formatted into strings or parsed from strings a culture is used to determine how it is done. E.g. in the dominant en-US culture you have these string representations:

  • 1,000,000.00 - one million with a two digit fraction
  • 1/29/2013 - date of this posting

In my culture (da-DK) the values have this string representation:

  • 1.000.000,00 - one million with a two digit fraction
  • 29-01-2013 - date of this posting

In the Windows operating system the user may even customize how numbers and date/times are formatted and may also choose another culture than the culture of his operating system. The formatting used is the choice of the user which is how it should be.

So when you format a value to be displayed to the user using for instance ToString or String.Format or parsed from a string using DateTime.Parse or Decimal.Parse the default is to use the CultureInfo.CurrentCulture. This allows the user to control the formatting.

However, a lot of string formatting and parsing is actually not strings exchanged between the application and the user but between the application and some data format (e.g. an XML or CSV file). In that case you don't want to use CultureInfo.CurrentCulture because if formatting and parsing is done with different cultures it can break. In that case you want to use CultureInfo.InvariantCulture (which is based on the en-US culture). This ensures that the values can roundtrip without problems.

The reason that ReSharper gives you the warning is that some application writers are unaware of this distinction which may lead to unintended results but they never discover this because their CultureInfo.CurrentCulture is en-US which has the same behavior as CultureInfo.InvariantCulture. However, as soon as the application is used in another culture where there is a chance of using one culture for formatting and another for parsing the application may break.

So to sum it up:

  • Use CultureInfo.CurrentCulture (the default) if you are formatting or parsing a user string.
  • Use CultureInfo.InvariantCulture if you are formatting or parsing a string that should be parseable by a piece of software.
  • Rarely use a specific national culture because the user is unable to control how formatting and parsing is done.

How can I dynamically switch web service addresses in .NET without a recompile?

Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

How to tell if a JavaScript function is defined

Most if not all previous answers have side effects to invoke the function

here best practice

you have function

_x000D_
_x000D_
function myFunction() {_x000D_
        var x=1;_x000D_
    }
_x000D_
_x000D_
_x000D_ direct way to test for it

_x000D_
_x000D_
//direct way_x000D_
        if( (typeof window.myFunction)=='function')_x000D_
            alert('myFunction is function')_x000D_
        else_x000D_
            alert('myFunction is not defined');
_x000D_
_x000D_
_x000D_ using a string so you can have only one place to define function name

_x000D_
_x000D_
//byString_x000D_
        var strFunctionName='myFunction'_x000D_
        if( (typeof window[strFunctionName])=='function')_x000D_
            alert(s+' is function');_x000D_
        else_x000D_
            alert(s+' is not defined');
_x000D_
_x000D_
_x000D_

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

install beautiful soup using pip

pip is a command line tool, not Python syntax.

In other words, run the command in your console, not in the Python interpreter:

pip install beautifulsoup4

You may have to use the full path:

C:\Python27\Scripts\pip install beautifulsoup4

or even

C:\Python27\Scripts\pip.exe install beautifulsoup4

Windows will then execute the pip program and that will use Python to install the package.

Another option is to use the Python -m command-line switch to run the pip module, which then operates exactly like the pip command:

python -m pip install beautifulsoup4

or

python.exe -m pip install beautifulsoup4

How can I display the current branch and folder path in terminal?

Based on 6LYTH3's answer I've decided to post my own due to some improvements that may come in handy:

Simple solution

Open ~/.bash_profile and add the following content

# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
#  \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'

# determines if the git branch you are on is clean or dirty
git_prompt ()
{
  # Is this a git directory?
  if ! git rev-parse --git-dir > /dev/null 2>&1; then
    return 0
  fi
  # Grab working branch name
  git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
  # Clean or dirty branch
  if git diff --quiet 2>/dev/null >&2; then
    git_color="${git_clean_color}"
  else
    git_color="${git_dirty_color}"
  fi
  echo " [$git_color$git_branch${reset_color}]"
}

export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"

This should:

1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color 
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.

You can customize the colors with this list

Sophisticated Solution

Another option is to use Git Bash Prompt, install with this. I used the option via Homebrew on Mac OS X.

git_prompt_list_themes to see the themes but I didn't like any of them.

git_prompt_color_samples to see available colors.

git_prompt_make_custom_theme [<Name of base theme>] to create a new custom theme, this should create a .git-prompt-colors.sh file.

subl ~/.git-prompt-colors.sh to open git-prompt-colors.sh and customize:

The .git-prompt-colors.sh file should look like this with my customization

    override_git_prompt_colors() {
      GIT_PROMPT_THEME_NAME="Custom"

      # Clean or dirty branch
      if git diff --quiet 2>/dev/null >&2; then
        GIT_PROMPT_BRANCH="${Green}"
      else
        GIT_PROMPT_BRANCH="${Red}"
      fi
    }

    reload_git_prompt_colors "Custom"

Hope this helps, have a great day!

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

Array to Collection: Optimized code

Have you checked Arrays.asList(); see API

No @XmlRootElement generated by JAXB

The topic is quite old but still relevant in enterprise business contexts. I tried to avoid to touch the xsds in order to easily update them in the future. Here are my solutions..

1. Mostly xjc:simple is sufficient

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jxb:extensionBindingPrefixes="xjc">

    <jxb:globalBindings>
        <xjc:simple/> <!-- adds @XmlRootElement annotations -->
    </jxb:globalBindings>

</jxb:bindings>

It will mostly create XmlRootElements for importing xsd definitions.

2. Divide your jaxb2-maven-plugin executions

I have encountered that it makes a huge difference if you try to generate classes from multiple xsd definitions instead of a execution definition per xsd.

So if you have a definition with multiple <source>'s, than just try to split them:

          <execution>
            <id>xjc-schema-1</id>
            <goals>
              <goal>xjc</goal>
            </goals>
            <configuration>
              <xjbSources>
                <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
              </xjbSources>
              <sources>
                <source>src/main/resources/xsd/definition1/</source>
              </sources>
              <clearOutputDir>false</clearOutputDir>
            </configuration>
          </execution>

          <execution>
            <id>xjc-schema-2</id>
            <goals>
              <goal>xjc</goal>
            </goals>
            <configuration>
              <xjbSources>
                <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
              </xjbSources>
              <sources>
                <source>src/main/resources/xsd/definition2/</source>
              </sources>
              <clearOutputDir>false</clearOutputDir>
            </configuration>
          </execution>

The generator will not catch the fact that one class might be sufficient and therefore create custom classes per execution. And thats exactly what I need ;).

CSS3 Box Shadow on Top, Left, and Right Only

#div:before {
 content:"";
 position:absolute;
 width:100%;
 background:#fff;
 height:38px;
 top:1px;
 right:-5px;
}

POST Multipart Form Data using Retrofit 2.0 including image

There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

Define API interface:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart); 
                                   // You can add other parameters too

Upload file like this:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

Java Array, Finding Duplicates

This program will print all duplicates value from array.

public static void main(String[] args) {

    int[] array = new int[] { -1, 3, 4, 4,4,3, 9,-1, 5,5,5, 5 };
    
    Arrays.sort(array);

 boolean isMatched = false;
 int lstMatch =-1;
      for(int i = 0; i < array.length; i++) {  
          try {
                if(array[i] == array[i+1]) { 
                    isMatched = true;
                    lstMatch = array[i+1]; 
                }
                else if(isMatched) {
                    System.out.println(lstMatch);
                    isMatched = false;
                    lstMatch = -1;
                }
          }catch(Exception ex) {
              //TODO NA
          }

      }
      if(isMatched) {
          System.out.println(lstMatch);
      }

}

}

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Using the data.table package, which is fast (useful for larger datasets)

https://github.com/Rdatatable/data.table/wiki

library(data.table)
df2 <- setDT(df1)[, lapply(.SD, sum), by=.(year, month), .SDcols=c("x1","x2")]
setDF(df2) # convert back to dataframe

Using the plyr package

require(plyr)
df2 <- ddply(df1, c("year", "month"), function(x) colSums(x[c("x1", "x2")]))

Using summarize() from the Hmisc package (column headings are messy in my example though)

# need to detach plyr because plyr and Hmisc both have a summarize()
detach(package:plyr)
require(Hmisc)
df2 <- with(df1, summarize( cbind(x1, x2), by=llist(year, month), FUN=colSums))

Xcode 4: How do you view the console?

If you just want to have the log output display when you run your app then you can go into XCode4 preferences -> Alerts and click on 'Run starts' on the left hand column.

Then select 'Show Debugger' and when you run the app the NSLog output will be displayed below the editor pane.

This way you don't have to select on the 'up arrow' button at the bottom bar.

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

In Java, what is the best way to determine the size of an object?

I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a costly thing to do. There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.

One way you could do it is to serialize the thing to a File and look at the size of the file, like this:

Serializable myObject;
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));
oos.write (myObject);
oos.close ();

Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.

Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy. But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.

HTML5 Canvas: Zooming

Just try this out:

<!DOCTYPE HTML>
<html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }

            #wrapper {
                position: relative;
                border: 1px solid #9C9898;
                width: 578px;
                height: 200px;
            }

            #buttonWrapper {
                position: absolute;
                width: 30px;
                top: 2px;
                right: 2px;
            }

            input[type =
            "button"] {
                padding: 5px;
                width: 30px;
                margin: 0px 0px 2px 0px;
            }
        </style>
        <script>
            function draw(scale, translatePos){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");

                // clear canvas
                context.clearRect(0, 0, canvas.width, canvas.height);

                context.save();
                context.translate(translatePos.x, translatePos.y);
                context.scale(scale, scale);
                context.beginPath(); // begin custom shape
                context.moveTo(-119, -20);
                context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
                context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
                context.bezierCurveTo(131, 50, 131, 20, 101, 0);
                context.bezierCurveTo(141, -60, 81, -70, 51, -50);
                context.bezierCurveTo(31, -95, -39, -80, -39, -50);
                context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
                context.closePath(); // complete custom shape
                var grd = context.createLinearGradient(-59, -100, 81, 100);
                grd.addColorStop(0, "#8ED6FF"); // light blue
                grd.addColorStop(1, "#004CB3"); // dark blue
                context.fillStyle = grd;
                context.fill();

                context.lineWidth = 5;
                context.strokeStyle = "#0000ff";
                context.stroke();
                context.restore();
            }

            window.onload = function(){
                var canvas = document.getElementById("myCanvas");

                var translatePos = {
                    x: canvas.width / 2,
                    y: canvas.height / 2
                };

                var scale = 1.0;
                var scaleMultiplier = 0.8;
                var startDragOffset = {};
                var mouseDown = false;

                // add button event listeners
                document.getElementById("plus").addEventListener("click", function(){
                    scale /= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                document.getElementById("minus").addEventListener("click", function(){
                    scale *= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                // add event listeners to handle screen drag
                canvas.addEventListener("mousedown", function(evt){
                    mouseDown = true;
                    startDragOffset.x = evt.clientX - translatePos.x;
                    startDragOffset.y = evt.clientY - translatePos.y;
                });

                canvas.addEventListener("mouseup", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseover", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseout", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mousemove", function(evt){
                    if (mouseDown) {
                        translatePos.x = evt.clientX - startDragOffset.x;
                        translatePos.y = evt.clientY - startDragOffset.y;
                        draw(scale, translatePos);
                    }
                });

                draw(scale, translatePos);
            };



            jQuery(document).ready(function(){
               $("#wrapper").mouseover(function(e){
                  $('#status').html(e.pageX +', '+ e.pageY);
               }); 
            })  
        </script>
    </head>
    <body onmousedown="return false;">
        <div id="wrapper">
            <canvas id="myCanvas" width="578" height="200">
            </canvas>
            <div id="buttonWrapper">
                <input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
            </div>
        </div>
        <h2 id="status">
        0, 0
        </h2>
    </body>
</html>

Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!

Here is fiddle for this Fiddle

Reset MySQL root password using ALTER USER statement after install on Mac

remember versions 5.7.23 and up - the user table doesn't has column password instead authentication string so below works while resetting password for a user.

update user set authentication_string=password('root') where user='root';

count number of rows in a data frame in R based on group

Suppose we have a df_data data frame as below

> df_data
   ID MONTH-YEAR VALUE
1 110   JAN.2012  1000
2 111   JAN.2012  2000
3 121   FEB.2012  3000
4 131   FEB.2012  4000
5 141   MAR.2012  5000

To count number of rows in df_data grouped by MONTH-YEAR column, you can use:

> summary(df_data$`MONTH-YEAR`)

FEB.2012 JAN.2012 MAR.2012 
   2        2        1 

enter image description here summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)

Pass a String from one Activity to another Activity in Android

private final String easyPuzzle ="630208010200050089109060030"+
                             "008006050000187000060500900"+
                             "09007010681002000502003097";
Bundle ePzl= new Bundle();
ePzl.putString("key", easyPuzzle);

Intent i = new Intent(MainActivity.this,AnotherActivity.class);
i.putExtras(ePzl);
startActivity(i);

Now go to AnotherActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_activity);

    Bundle p = getIntent().getExtras();
    String yourPreviousPzl =p.getString("key");

}

now "yourPreviousPzl" is your desired string.

Targeting only Firefox with CSS

Now that Firefox Quantum 57 is out with substantial — and potentially breaking — improvements to Gecko collectively known as Stylo or Quantum CSS, you may find yourself in a situation where you have to distinguish between legacy versions of Firefox and Firefox Quantum.

From my answer here:

You can use @supports with a calc(0s) expression in conjunction with @-moz-document to test for Stylo — Gecko does not support time values in calc() expressions but Stylo does:

@-moz-document url-prefix() {
  @supports (animation: calc(0s)) {
    /* Stylo */
  }
}

Here's a proof-of-concept:

_x000D_
_x000D_
body::before {_x000D_
  content: 'Not Fx';_x000D_
}_x000D_
_x000D_
@-moz-document url-prefix() {_x000D_
  body::before {_x000D_
    content: 'Fx legacy';_x000D_
  }_x000D_
_x000D_
  @supports (animation: calc(0s)) {_x000D_
    body::before {_x000D_
      content: 'Fx Quantum';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Targeting legacy versions of Firefox is a little tricky — if you're only interested in versions that support @supports, which is Fx 22 and up, @supports not (animation: calc(0s)) is all you need:

@-moz-document url-prefix() {
  @supports not (animation: calc(0s)) {
    /* Gecko */
  }
}

... but if you need to support even older versions, you'll need to make use of the cascade, as demonstrated in the proof-of-concept above.

Using R to download zipped data file, extract, and import data

To do this using data.table, I found that the following works. Unfortunately, the link does not work anymore, so I used a link for another data set.

library(data.table)
temp <- tempfile()
download.file("https://www.bls.gov/tus/special.requests/atusact_0315.zip", temp)
timeUse <- fread(unzip(temp, files = "atusact_0315.dat"))
rm(temp)

I know this is possible in a single line since you can pass bash scripts to fread, but I am not sure how to download a .zip file, extract, and pass a single file from that to fread.

Eclipse error "Could not find or load main class"

if your package name is same with your class name this problem will occur.

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

How to append to the end of an empty list?

You don't need the assignment operator. append returns None.

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

Failed to load AppCompat ActionBar with unknown error in android studio

I also had this problem with implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'.

The solution for me was to go File -> Invalidate Caches / Restart -> Invalidate -> Close Project -> Remove project from project window -> Open Project (from project window).

How to Convert the value in DataTable into a string array in c#

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Try with,

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

instead of,

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

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Anybody knows any knowledge base open source?

In addition to MediaWiki that was mentioned by Kenny, you might also look at MoinMoin.

Choosing between MediaWiki and MoinMoin can be a bit tough. Here are some points to consider:

MediaWiki

Pros:

  • Made for wikipedia, thus is very mature and scalable.
  • Fairly easy to set up.

    Cons:

  • Made soley for wikipedia. Thus it can be a bit of a pain to customize how you like it.

MoinMoin

Pros:

  • Very mature software.
  • Huge amount of plugins and third party modules available.

    Cons:

  • Can be a pain to install.

There are a huge amount of other wikis available, but those are the main two I would consider.

How to trigger a click on a link using jQuery

We can do it in many ways...

CASE - 1

We can use trigger like this : $("#myID").trigger("click");

CASE - 2

We can use click() function like this : $("#myID").click();

CASE - 3

If we want to write function on programmatically click then..

$("#myID").click(function() {
  console.log("Clicked");
// Do here whatever you want
});

CASE - 4

// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );  

Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/

Making authenticated POST requests with Spring RestTemplate for Android

I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.

What worked for me was encoding credentials in Base64 and adding them as Basic Authorization headers. I then added them as an HttpEntity to restTemplate.postForEntity, which gave me the response I needed.

Here's the class I wrote for this in full (extending RestTemplate):

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

    public AuthorizedRestTemplate(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getForObject(String url, Object... urlVariables){
        return authorizedRestCall(this, url, urlVariables);
    }

    private String authorizedRestCall(RestTemplate restTemplate, 
            String url, Object... urlVariables){
        HttpEntity<String> request = getRequest();
        ResponseEntity<String> entity = restTemplate.postForEntity(url, 
                request, String.class, urlVariables);
        return entity.getBody();
    }

    private HttpEntity<String> getRequest(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + getBase64Credentials());
        return new HttpEntity<String>(headers);
    }

    private String getBase64Credentials(){
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Can I find events bound on an element with jQuery?

In modern versions of jQuery, you would use the $._data method to find any events attached by jQuery to the element in question. Note, this is an internal-use only method:

// Bind up a couple of event handlers
$("#foo").on({
    click: function(){ alert("Hello") },
    mouseout: function(){ alert("World") }
});

// Lookup events for this particular Element
$._data( $("#foo")[0], "events" );

The result from $._data will be an object that contains both of the events we set (pictured below with the mouseout property expanded):

Console output for $._

Then in Chrome, you may right click the handler function and click "view function definition" to show you the exact spot where it is defined in your code.

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

How do I add a simple jQuery script to WordPress?

You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/

When you use jQuery don't forget use jquery noconflict mode

How to copy to clipboard in Vim?

if you connect to the unix system thru putty then follow the steps below to copy content of a file

  • Highlight text you want to copy ( you'll be able to copy page by page )
  • press ctrl+c ( it'll copy the text to clipboard
  • paste in any external editor Done

$(document).ready equivalent without jQuery

This cross-browser code will call a function once the DOM is ready:

var domReady=function(func){
    var scriptText='('+func+')();';
    var scriptElement=document.createElement('script');
    scriptElement.innerText=scriptText;
    document.body.appendChild(scriptElement);
};

Here's how it works:

  1. The first line of domReady calls the toString method of the function to get a string representation of the function you pass in and wraps it in an expression that immediately calls the function.
  2. The rest of domReady creates a script element with the expression and appends it to the body of the document.
  3. The browser runs script tags appended to body after the DOM is ready.

For example, if you do this: domReady(function(){alert();});, the following will appended to the body element:

 <script>(function (){alert();})();</script>

Note that this works only for user-defined functions. The following won't work: domReady(alert);

Get random boolean in Java

You can use the following for an unbiased result:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!

If you want to give more probability to your result to be true (or false) you can adjust the above as following!

Random random = new Random();

//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;

//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;

Twitter Bootstrap button click to toggle expand/collapse text section above button

It's possible to do this without using extra JS code using the data-collapse and data-target attributes on the a link.

e.g.

<a class="btn" data-toggle="collapse" data-target="#viewdetails">View details &raquo;</a>

Here's a working example.

How to use multiprocessing queue in Python?

We implemented two versions of this, one a simple multi thread pool that can execute many types of callables, making our lives much easier and the second version that uses processes, which is less flexible in terms of callables and requires and extra call to dill.

Setting frozen_pool to true will freeze execution until finish_pool_queue is called in either class.

Thread Version:

'''
Created on Nov 4, 2019

@author: Kevin
'''
from threading import Lock, Thread
from Queue import Queue
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os

class ThreadPool(object):
    def __init__(self, queue_threads, *args, **kwargs):
        self.frozen_pool = kwargs.get('frozen_pool', False)
        self.print_queue = kwargs.get('print_queue', True)
        self.pool_results = []
        self.lock = Lock()
        self.queue_threads = queue_threads
        self.queue = Queue()
        self.threads = []

        for i in range(self.queue_threads):
            t = Thread(target=self.make_pool_call)
            t.daemon = True
            t.start()
            self.threads.append(t)

    def make_pool_call(self):
        while True:
            if self.frozen_pool:
                #print '--> Queue is frozen'
                sleep(1)
                continue

            item = self.queue.get()
            if item is None:
                break

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.lock.acquire()
                    self.pool_results.append((item, result))
                    self.lock.release()

            except Exception as e:
                self.lock.acquire()
                print e
                traceback.print_exc()
                self.lock.release()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self):
        self.frozen_pool = False

        while self.queue.unfinished_tasks > 0:
            if self.print_queue:
                print_info('--> Thread pool... %s' % self.queue.unfinished_tasks)
            sleep(5)

        self.queue.join()

        for i in range(self.queue_threads):
            self.queue.put(None)

        for t in self.threads:
            t.join()

        del self.threads[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]

Process Version:

  '''
Created on Nov 4, 2019

@author: Kevin
'''
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os
from multiprocessing import Queue, Process, Value, Array, JoinableQueue, Lock,\
    RawArray, Manager
from dill import dill
import ctypes
from helium.misc.utils import ignore_exception
from mem_top import mem_top
import gc

class ProcessPool(object):
    def __init__(self, queue_processes, *args, **kwargs):
        self.frozen_pool = Value(ctypes.c_bool, kwargs.get('frozen_pool', False))
        self.print_queue = kwargs.get('print_queue', True)
        self.manager = Manager()
        self.pool_results = self.manager.list()
        self.queue_processes = queue_processes
        self.queue = JoinableQueue()
        self.processes = []

        for i in range(self.queue_processes):
            p = Process(target=self.make_pool_call)
            p.start()
            self.processes.append(p)

        print 'Processes', self.queue_processes

    def make_pool_call(self):
        while True:
            if self.frozen_pool.value:
                sleep(1)
                continue

            item_pickled = self.queue.get()

            if item_pickled is None:
                #print '--> Ending'
                self.queue.task_done()
                break

            item = dill.loads(item_pickled)

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.pool_results.append(dill.dumps((item, result)))
                else:
                    del call, args, kwargs, keep_results, item, result

            except Exception as e:
                print e
                traceback.print_exc()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self, callable=None):
        self.frozen_pool.value = False

        while self.queue._unfinished_tasks.get_value() > 0:
            if self.print_queue:
                print_info('--> Process pool... %s' % (self.queue._unfinished_tasks.get_value()))

            if callable:
                callable()

            sleep(5)

        for i in range(self.queue_processes):
            self.queue.put(None)

        self.queue.join()
        self.queue.close()

        for p in self.processes:
            with ignore_exception: p.join(10)
            with ignore_exception: p.terminate()

        with ignore_exception: del self.processes[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]
def test(eg):
        print 'EG', eg

Call with either:

tp = ThreadPool(queue_threads=2)
tp.queue.put({'call': test, 'args': [random.randint(0, 100)]})
tp.finish_pool_queue()

or

pp = ProcessPool(queue_processes=2)
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.finish_pool_queue()

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

Interface vs Abstract Class (general OO)

Conceptually speaking, keeping the language specific implementation, rules, benefits and achieving any programming goal by using anyone or both, can or cant have code/data/property, blah blah, single or multiple inheritances, all aside

1- Abstract (or pure abstract) Class is meant to implement hierarchy. If your business objects look somewhat structurally similar, representing a parent-child (hierarchy) kind of relationship only then inheritance/Abstract classes will be used. If your business model does not have a hierarchy then inheritance should not be used (here I am not talking about programming logic e.g. some design patterns require inheritance). Conceptually, abstract class is a method to implement hierarchy of a business model in OOP, it has nothing to do with Interfaces, actually comparing Abstract class with Interface is meaningless because both are conceptually totally different things, it is asked in interviews just to check the concepts because it looks both provide somewhat same functionality when implementation is concerned and we programmers usually emphasize more on coding. [Keep this in mind as well that Abstraction is different than Abstract Class].

2- an Interface is a contract, a complete business functionality represented by one or more set of functions. That is why it is implemented and not inherited. A business object (part of a hierarchy or not) can have any number of complete business functionality. It has nothing to do with abstract classes means inheritance in general. For example, a human can RUN, an elephant can RUN, a bird can RUN, and so on, all these objects of different hierarchy would implement the RUN interface or EAT or SPEAK interface. Don't go into implementation as you might implement it as having abstract classes for each type implementing these interfaces. An object of any hierarchy can have a functionality(interface) which has nothing to do with its hierarchy.

I believe, Interfaces were not invented to achieve multiple inheritances or to expose public behavior, and similarly, pure abstract classes are not to overrule interfaces but Interface is a functionality that an object can do (via functions of that interface) and Abstract Class represents a parent of a hierarchy to produce children having core structure (property+functionality) of the parent

When you are asked about the difference, it is actually conceptual difference not the difference in language-specific implementation unless asked explicitly.

I believe, both interviewers were expecting one line straightforward difference between these two and when you failed they tried to drove you towards this difference by implementing ONE as the OTHER

What if you had an Abstract class with only abstract methods?

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

What are the differences between char literals '\n' and '\r' in Java?

On the command line, \r will move the cursor back to the beginning of the current line. To see the difference you must run your code from a command prompt. Eclipse's console show similar output for both the expression. For complete list of escape sequences, click here https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6

Can I install Python 3.x and 2.x on the same Windows computer?

Before I courageously installed both simultaneously, I had so many questions. If I give python will it go to py3 when i want py2? pip/virtualenv will happen under py2/3?

It seems to be very simple now.

Just blindly install both of them. Make sure you get the right type(x64/x32). While/after installing make sure you add to the path to your environment variables.

[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")

Replace the x in the command above to set the path.

Then go to both the folders.

Navigate to

python3.6/Scripts/

and rename pip to pip3.

If pip3 already exists delete the pip. This will make sure that just pip will run under python2. You can verify by:

pip --version

In case you want to use pip with python3 then just use

pip3 install 

You can similarly do the same to python file and others.

Cheers!

C++ - how to find the length of an integer

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length()

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Your vm does not find the class org/apache/juli/logging/LogFactory check if this class is present in the tomcat-juli.jar that you use (unzip it and search the file), if it's not present download the library from apache web site else if it's present put the tomcat-juli.jar in a path (the lib directory) that Tomcat use to load classes. If your Tomcat does not find it you can copy the jar in the lib directory of the JRE that you are using.

Why does the order in which libraries are linked sometimes cause errors in GCC?

A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.

You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.

How do I debug Node.js applications?

Node has its own built in GUI debugger as of version 6.3 (using Chrome's DevTools)

Nodes builtin GUI debugger

Simply pass the inspector flag and you'll be provided with a URL to the inspector:

node --inspect server.js

You can also break on the first line by passing --inspect-brk instead.

remove double quotes from Json return data using Jquery

Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.

Another way to do this that I don't see listed here is using:

let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message))              // Hello World

How to set Sqlite3 to be case insensitive when string comparing?

You can do it like this:

SELECT * FROM ... WHERE name LIKE 'someone'

(It's not the solution, but in some cases is very convenient)

"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."

How do I "un-revert" a reverted Git commit?

Or you could git checkout -b <new-branch> and git cherry-pick <commit> the before to the and git rebase to drop revert commit. send pull request like before.

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

How do I draw a grid onto a plot in Python?

To show a grid line on every tick, add

plt.grid(True)

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here


In addition, you might want to customize the styling (e.g. solid line instead of dashed line), add:

plt.rc('grid', linestyle="-", color='black')

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here

How to set background image in Java?

Or try this ;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

C# switch on type

I have used this form of switch-case on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.

If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.

Here is a little example expanding on Mark's solution. I think it is a great way to work with types:

Dictionary<Type, Action> typeTests;

public ClassCtor()
{
    typeTests = new Dictionary<Type, Action> ();

    typeTests[typeof(int)] = () => DoIntegerStuff();
    typeTests[typeof(string)] = () => DoStringStuff();
    typeTests[typeof(bool)] = () => DoBooleanStuff();
}

private void DoBooleanStuff()
{
   //do stuff
}

private void DoStringStuff()
{
    //do stuff
}

private void DoIntegerStuff()
{
    //do stuff
}

public Action CheckTypeAction(Type TypeToTest)
{
    if (typeTests.Keys.Contains(TypeToTest))
        return typeTests[TypeToTest];

    return null; // or some other Action delegate
}

Importing a long list of constants to a Python file

Python doesn't have a preprocessor, nor does it have constants in the sense that they can't be changed - you can always change (nearly, you can emulate constant object properties, but doing this for the sake of constant-ness is rarely done and not considered useful) everything. When defining a constant, we define a name that's upper-case-with-underscores and call it a day - "We're all consenting adults here", no sane man would change a constant. Unless of course he has very good reasons and knows exactly what he's doing, in which case you can't (and propably shouldn't) stop him either way.

But of course you can define a module-level name with a value and use it in another module. This isn't specific to constants or anything, read up on the module system.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT

Replace whole line containing a string using Sed

for manipulation of config files

i came up with this solution inspired by skensell answer

configLine [searchPattern] [replaceLine] [filePath]

it will:

  • create the file if not exists
  • replace the whole line (all lines) where searchPattern matched
  • add replaceLine on the end of the file if pattern was not found

Function:

function configLine {
  local OLD_LINE_PATTERN=$1; shift
  local NEW_LINE=$1; shift
  local FILE=$1
  local NEW=$(echo "${NEW_LINE}" | sed 's/\//\\\//g')
  touch "${FILE}"
  sed -i '/'"${OLD_LINE_PATTERN}"'/{s/.*/'"${NEW}"'/;h};${x;/./{x;q100};x}' "${FILE}"
  if [[ $? -ne 100 ]] && [[ ${NEW_LINE} != '' ]]
  then
    echo "${NEW_LINE}" >> "${FILE}"
  fi
}

the crazy exit status magic comes from https://stackoverflow.com/a/12145797/1262663