Programs & Examples On #Parent node

Print Html template in Angular 2 (ng-print in Angular 2)

In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();

component.html:

<div class="doNotPrint">
    Header is here.
</div>

<div>
    all my beautiful print-related material is here.
</div>

<div class="doNotPrint">
    my footer is here.
    <button (click)="onPrint()">Print</button>
</div>

component.ts:

onPrint(){
    window.print();
}

component.css:

@media print{
  .doNotPrint{display:none !important;}
}

You can optionally also add other elements / sections you do not wish to print in the media query.

You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes/ It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.

Shell script to copy files from one location to another location and rename add the current date to every file

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1
for f in *.csv
do 
   cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done

Changing button color programmatically

Try this code You may want something like this

<button class="normal" id="myButton" 
        value="Hover" onmouseover="mouseOver()" 
        onmouseout="mouseOut()">Some text</button>

Then on your .js file enter this.Make sure your html is connected to your .js

var tag=document.getElementById("myButton");

function mouseOver() {
    tag.style.background="yellow";
};
function mouseOut() {
    tag.style.background="white";
};

How to design RESTful search/filtering?

As I'm using a laravel/php backend I tend to go with something like this:

/resource?filters[status_id]=1&filters[city]=Sydney&page=2&include=relatedResource

PHP automatically turns [] params into an array, so in this example I'll end up with a $filter variable that holds an array/object of filters, along with a page and any related resources I want eager loaded.

If you use another language, this might still be a good convention and you can create a parser to convert [] to an array.

SQL: How to to SUM two values from different tables

SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result

'And so on and so forth.

"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source

how to specify local modules as npm package dependencies

npm install now supports this

npm install --save ../path/to/mymodule

For this to work mymodule must be configured as a module with its own package.json. See Creating NodeJS modules.

As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.

This feature was implemented in the version 2.0.0 of npm. For example:

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

Any of the following paths are also valid:

../foo/bar
~/foo/bar
./foo/bar
/foo/bar

syncing updates

Since npm install copies mymodule into node_modules, changes in mymodule's source will not automatically be seen by the dependent project.

There are two ways to update the dependent project with

  • Update the version of mymodule and then use npm update: As you can see above, the package.json "dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update just tries to make sure the latest version is installed, as determined by mymodule's package.json. See chriskelly's answer to this specific problem.

  • Reinstall using npm install. This will install whatever is at mymodule's source path, even if it is older, or has an alternate branch checked out, whatever.

Iterate through 2 dimensional array

Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.

String string="";
for (int i = 0; i<array.length; i++){
    for (int j = 0; j<array[i].length; j++){
        string = string.concat(array[j][i]);
    } 
}
System.out.println(string)

Cannot resolve symbol 'AppCompatActivity'

A little addition to other answers here, for anyone having the same error while using the right lib version and the right class.

When I upgraded to

appcompat-v7:22.1.0

In which ActionBarActivity is deprecated and empty and AppCompatActivty is the way to go, due to some glitch in Android Studio, It didn't quite pick up on version change.

i.e. Even though Gradle ran without errors, the IDE itself kept saying Cannot resolve symbol 'AppCompatActivity' (and it also wasn't available through the Ctrl+N search)

I looked into the .idea/libraries folder and noticed there's no appropriate metafile for the new version of the lib.

So, using the old-reliable File->Invalidate Caches/Restart did the trick. Always try this when you feel something is magically wrong with Android Studio. And then Disable offline mode and sync.

How do I set browser width and height in Selenium WebDriver?

It's easy. Here is the full code.

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("Your URL")
driver.set_window_size(480, 320)

Make sure chrome driver is in your system path.

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

retrieve links from web page using python and BeautifulSoup

Here's an example using @ars accepted answer and the BeautifulSoup4, requests, and wget modules to handle the downloads.

import requests
import wget
import os

from bs4 import BeautifulSoup, SoupStrainer

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/eeg-mld/eeg_full/'
file_type = '.tar.gz'

response = requests.get(url)

for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
    if link.has_attr('href'):
        if file_type in link['href']:
            full_path = url + link['href']
            wget.download(full_path)

How do I check which version of NumPy I'm using?

We can use pip freeze to get any Python package version without opening the Python shell.

pip freeze | grep 'numpy'

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Convert JS Object to form data

Maybe you're looking for this, a code that receive your javascript object, create a FormData object from it and then POST it to your server using new Fetch API:

    let myJsObj = {'someIndex': 'a value'};

    let datos = new FormData();
    for (let i in myJsObj){
        datos.append( i, myJsObj[i] );
    }

    fetch('your.php', {
        method: 'POST',
        body: datos
    }).then(response => response.json())
        .then(objson => {
            console.log('Success:', objson);
        })
        .catch((error) => {
            console.error('Error:', error);
        });

How to validate an OAuth 2.0 access token for a resource server?

OAuth 2.0 spec doesn't define the part. But there could be couple of options:

  1. When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.

  2. Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.

How to copy from CSV file to PostgreSQL table with headers in CSV file?

With the Python library pandas, you can easily create column names and infer data types from a csv file.

from sqlalchemy import create_engine
import pandas as pd

engine = create_engine('postgresql://user:pass@localhost/db_name')
df = pd.read_csv('/path/to/csv_file')
df.to_sql('pandas_db', engine)

The if_exists parameter can be set to replace or append to an existing table, e.g. df.to_sql('pandas_db', engine, if_exists='replace'). This works for additional input file types as well, docs here and here.

How can I split a string with a string delimiter?

You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.


You can also use regular expression. A simple google search turned out with this

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {
        Console.WriteLine(line);
    }
  }
}

Where does PHP's error log reside in XAMPP?

\xampp\apache\logs\error.log, where xampp is your installation folder. If you haven't changed the error_log setting in PHP (check with phpinfo()), it will be logged to the Apache log.

jquery's append not working with svg element?

I can see circle in firefox, doing 2 things:

1) Renaming file from html to xhtml

2) Change script to

<script type="text/javascript">
$(document).ready(function(){
    var obj = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    obj.setAttributeNS(null, "cx", 100);
    obj.setAttributeNS(null, "cy", 50);
    obj.setAttributeNS(null, "r",  40);
    obj.setAttributeNS(null, "stroke", "black");
    obj.setAttributeNS(null, "stroke-width", 2);
    obj.setAttributeNS(null, "fill", "red");
    $("svg")[0].appendChild(obj);
});
</script>

Should I use SVN or Git?

I would probably choose Git because I feel it's much more powerful than SVN. There are cheap Code Hosting services available which work just great for me - you don't have to do backups or any maintenance work - GitHub is the most obvious candidate.

That said, I don't know anything regarding the integration of Visual Studio and the different SCM systems. I imagine the integration with SVN to notably better.

Row count on the Filtered data

I know this an old thread, but I found out using the Subtotal method in VBA also accurately renders a count of the rows. The formula I found is in this article, and looks like this:

Application.WorksheetFunction.Subtotal(2, .Range("A2:A" & .Rows(.Rows.Count).End(xlUp).Row))

I tested it and it came out accurately every time, rendering the correct number of visible rows in column A.

Hopefully this will help some other wayfarer of the 'Net like me.

How to disable XDebug

Comment extension in php.ini and restart Apache. Here is a simple script (you can assign shortcut to it)

xdebug-toggle.php

define('PATH_TO_PHP_INI', 'c:/xampp/php/php.ini');
define('PATH_TO_HTTPD', 'c:/xampp/apache/bin/httpd.exe');
define('REXP_EXTENSION', '(zend_extension\s*=.*?php_xdebug)');

$s = file_get_contents(PATH_TO_PHP_INI);
$replaced = preg_replace('/;' . REXP_EXTENSION . '/', '$1', $s);
$isOn = $replaced != $s;
if (!$isOn) {
    $replaced = preg_replace('/' . REXP_EXTENSION . '/', ';$1', $s);
}
echo 'xdebug is ' . ($isOn ? 'ON' : 'OFF') . " now. Restarting apache...\n\n";
file_put_contents(PATH_TO_PHP_INI, $replaced);

passthru(PATH_TO_HTTPD . ' -k restart');

How to add a touch event to a UIView?

Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan. You can add it to the view after that.

This way you'll use composition instead subclassing (which was the request).

Set default value of javascript object attributes

This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.

var defaults = {
    a: 'test1',
    b: 'test2'
};

Then when you create your properties object you do it with Object.create

properties = Object.create(defaults);

Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:

console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));

What is the purpose of a self executing function in javascript?

Namespacing. JavaScript's scopes are function-level.

How to align input forms in HTML

Well for the very basics you can try aligning them in the table. However the use of table is bad for layout since table is meant for contents.

What you can use is CSS floating techniques.

CSS Code

.styleform label{float:left;}
.styleform input{margin-left:200px;} /* this gives space for the label on the left */
.styleform .clear{clear:both;} /* prevent elements from stacking weirdly */

HTML

<div class="styleform">
<form>
<label>First Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Last Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Email:</label><input type="text" name="first" /><div class="clear"></div>
</form>
</div>

An elaborated article I wrote can be found answering the question of IE7 float problem: IE7 float right problems

A cycle was detected in the build path of project xxx - Build Path Problem

Problem

I have an old project that tests two different implementations of a Dictionary interface. One is an unsorted ArrayList and the other is a HashTable. The two implementations are timed, so that a comparison can be made. You can choose which data structure from the command line args. Now.. I have another data structure which is a tree structure. I want to test the time of it, in order to compare it to the HashTable. So.. In the new dataStructure project, I need to implement the Dictionary interface. In the Dictionary project, I need to be able to add code specific to my new dataStructure project. There is a circular dependency. This means that when Eclipse goes to find out which projects are dependent on project A, then it finds project B. When it needs to find out the sub-dependencies of the dependent projects, it finds A, which is again, dependent on B. There is no tree, rather a graph with a cycle.

Solution

When you go to configure your build path, instead of entering dependent projects ('projects' tab), go to the Libraries tab. Click the 'Add Class Folder...' button (assuming that your referenced projects are in your workspace), and select the class folder. Mine is \target. Select this as a library folder. Do this in project A, to reference project B. Do this in project B to reference project A. Make sure that you don't reference \target\projectNameFolder or you won't have a matching import. Now you won't have to remove a dependency and then reset it, in order to force a rebuild.

Use class libraries instead of project references.

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to press/click the button using Selenium if the button does not have the Id?

use the text and value attributes instead of the id

driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();

similarly for Next.

How to get the difference (only additions) between two files in linux

git diff path/file.css | grep -E "^\+" | grep -v '+++ b/' | cut -c 2-
  • grep -E "^\+" is from previous accepted answer, it is incomplete because leaves non-source stuff
  • grep -v '+++ b' removes non-source line with file name of later version
  • cut -c 2- removes column of + signs, also may use sed 's/^\+//'

comm or sdiff were not an option because of git.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.

Call a REST API in PHP

If you are open to use third party tools you'd have a look at this one: https://github.com/CircleOfNice/DoctrineRestDriver

This is a completely new way to work with APIs.

First of all you define an entity which is defining the structure of incoming and outcoming data and annotate it with datasources:

/*
 * @Entity
 * @DataSource\Select("http://www.myApi.com/products/{id}")
 * @DataSource\Insert("http://www.myApi.com/products")
 * @DataSource\Select("http://www.myApi.com/products/update/{id}")
 * @DataSource\Fetch("http://www.myApi.com/products")
 * @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
 */
class Product {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

Now it's pretty easy to communicate with the REST API:

$product = new Product();
$product->setName('test');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();

$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();

Changing ImageView source

You're supposed to use setImageResource instead of setBackgroundResource.

Change jsp on button click

It works using ajax. The jsp then display in iframe returned by controller in response to request.

function openPage() {
  jQuery.ajax({
  type : 'POST',
  data : jQuery(this).serialize(),
  url : '<%=request.getContextPath()%>/post_action',
  success : function(data, textStatus) {
  jQuery('#iframeId').contents().find('body').append(data);
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
  }
  });
}

How do I size a UITextView to its content?

We can do it by constraints .

  1. Set Height constraints for UITextView. enter image description here

2.Create IBOutlet for that height constraint.

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;

3.don't forget to set delegate for your textview.

4.

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
    [UIView animateWithDuration:0.2 animations:^{
                  _txtheightconstraints.constant=newFrame.size.height;
    }];

}

then update your constraint like this :)

Command not found after npm install in zsh

add source /home/YOUUSERNAME/.bash_profile at the beginning of ~/.zshrc

And all missing commands will be detected.

For Mac users : add source /Users/YOUUSERNAME/.bash_profile

How does numpy.newaxis work and when to use it?

What is np.newaxis?

The np.newaxis is just an alias for the Python constant None, which means that wherever you use np.newaxis you could also use None:

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)

Are there alternatives to np.newaxis?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shape you could also reshape the array to add these dimensions:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxis is the easiest way to add dimensions, but it's good to know the alternatives.

When to use np.newaxis?

In several contexts is adding dimensions useful:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow to display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])

jQuery javascript regex Replace <br> with \n

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example

edit: added i flag

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

How to change lowercase chars to uppercase using the 'keyup' event?

$(document).ready(function()
{
    $('#yourtext').keyup(function()
    {
        $(this).val($(this).val().toUpperCase());
    });
});

<textarea id="yourtext" rows="5" cols="20"></textarea>

Deleting Row in SQLite in Android

To delete rows from a table, you need to provide selection criteria that identify the rows to the delete() method. The mechanism works the same as the selection arguments to the query() method. It divides the selection specification into a selection clause(where clause) and selection arguments.

    SQLiteDatabase db  = this.getWritableDatabase();
     // Define 'where' part of query.
    String selection = Contract.COLUMN_COMPANY_ID + " =?  and "
                       + Contract.CLOUMN_TYPE +" =? ";
   // Specify arguments in placeholder order.
    String[] selectionArgs = { cid,mode };
    // Issue SQL statement.
    int deletedRows = db.delete(Contract.TABLE_NAME, 
                       selection, selectionArgs);
    return deletedRows;// no.of rows deleted.

The return value for the delete() method indicates the number of rows that were deleted from the database.

Pan & Zoom Image

Yet another version of the same kind of control. It has similar functionality as the others, but it adds:

  1. Touch support (drag/pinch)
  2. The image can be deleted (normally, the Image control locks the image on disk, so you cannot delete it).
  3. An inner border child, so the panned image doesn't overlap the border. In case of borders with rounded rectangles, look for ClippedBorder classes.

Usage is simple:

<Controls:ImageViewControl ImagePath="{Binding ...}" />

And the code:

public class ImageViewControl : Border
{
    private Point origin;
    private Point start;
    private Image image;

    public ImageViewControl()
    {
        ClipToBounds = true;
        Loaded += OnLoaded;
    }

    #region ImagePath

    /// <summary>
    ///     ImagePath Dependency Property
    /// </summary>
    public static readonly DependencyProperty ImagePathProperty = DependencyProperty.Register("ImagePath", typeof (string), typeof (ImageViewControl), new FrameworkPropertyMetadata(string.Empty, OnImagePathChanged));

    /// <summary>
    ///     Gets or sets the ImagePath property. This dependency property 
    ///     indicates the path to the image file.
    /// </summary>
    public string ImagePath
    {
        get { return (string) GetValue(ImagePathProperty); }
        set { SetValue(ImagePathProperty, value); }
    }

    /// <summary>
    ///     Handles changes to the ImagePath property.
    /// </summary>
    private static void OnImagePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = (ImageViewControl) d;
        var oldImagePath = (string) e.OldValue;
        var newImagePath = target.ImagePath;
        target.ReloadImage(newImagePath);
        target.OnImagePathChanged(oldImagePath, newImagePath);
    }

    /// <summary>
    ///     Provides derived classes an opportunity to handle changes to the ImagePath property.
    /// </summary>
    protected virtual void OnImagePathChanged(string oldImagePath, string newImagePath)
    {
    }

    #endregion

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        image = new Image {
                              //IsManipulationEnabled = true,
                              RenderTransformOrigin = new Point(0.5, 0.5),
                              RenderTransform = new TransformGroup {
                                                                       Children = new TransformCollection {
                                                                                                              new ScaleTransform(),
                                                                                                              new TranslateTransform()
                                                                                                          }
                                                                   }
                          };
        // NOTE I use a border as the first child, to which I add the image. I do this so the panned image doesn't partly obscure the control's border.
        // In case you are going to use rounder corner's on this control, you may to update your clipping, as in this example:
        // http://wpfspark.wordpress.com/2011/06/08/clipborder-a-wpf-border-that-clips/
        var border = new Border {
                                    IsManipulationEnabled = true,
                                    ClipToBounds = true,
                                    Child = image
                                };
        Child = border;

        image.MouseWheel += (s, e) =>
                                {
                                    var zoom = e.Delta > 0
                                                   ? .2
                                                   : -.2;
                                    var position = e.GetPosition(image);
                                    image.RenderTransformOrigin = new Point(position.X / image.ActualWidth, position.Y / image.ActualHeight);
                                    var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                    st.ScaleX += zoom;
                                    st.ScaleY += zoom;
                                    e.Handled = true;
                                };

        image.MouseLeftButtonDown += (s, e) =>
                                         {
                                             if (e.ClickCount == 2)
                                                 ResetPanZoom();
                                             else
                                             {
                                                 image.CaptureMouse();
                                                 var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                                 start = e.GetPosition(this);
                                                 origin = new Point(tt.X, tt.Y);
                                             }
                                             e.Handled = true;
                                         };

        image.MouseMove += (s, e) =>
                               {
                                   if (!image.IsMouseCaptured) return;
                                   var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                   var v = start - e.GetPosition(this);
                                   tt.X = origin.X - v.X;
                                   tt.Y = origin.Y - v.Y;
                                   e.Handled = true;
                               };

        image.MouseLeftButtonUp += (s, e) => image.ReleaseMouseCapture();

        //NOTE I apply the manipulation to the border, and not to the image itself (which caused stability issues when translating)!
        border.ManipulationDelta += (o, e) =>
                                       {
                                           var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                           var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);

                                           st.ScaleX *= e.DeltaManipulation.Scale.X;
                                           st.ScaleY *= e.DeltaManipulation.Scale.X;
                                           tt.X += e.DeltaManipulation.Translation.X;
                                           tt.Y += e.DeltaManipulation.Translation.Y;

                                           e.Handled = true;
                                       };
    }

    private void ResetPanZoom()
    {
        var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        st.ScaleX = st.ScaleY = 1;
        tt.X = tt.Y = 0;
        image.RenderTransformOrigin = new Point(0.5, 0.5);
    }

    /// <summary>
    /// Load the image (and do not keep a hold on it, so we can delete the image without problems)
    /// </summary>
    /// <see cref="http://blogs.vertigo.com/personal/ralph/Blog/Lists/Posts/Post.aspx?ID=18"/>
    /// <param name="path"></param>
    private void ReloadImage(string path)
    {
        try
        {
            ResetPanZoom();
            // load the image, specify CacheOption so the file is not locked
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
            bitmapImage.EndInit();
            image.Source = bitmapImage;
        }
        catch (SystemException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Send email using java

It has been quite a while since this has been posted. But as of Nov 13, 2012 I can verify that port 465 still works.

Refer to GaryM's answer on this forum. I hope this helps few more people.

/*
* Created on Feb 21, 2005
*
*/

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleTest {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "" };


    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
            emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully mail to All Users");
    }

    public void sendSSLMessage(String recipients[], String subject,
                               String message, String from) throws MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxx", "xxxxxx");
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
}

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

With MySQL, how can I generate a column containing the record index in a table?

SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo

How to populate a dropdownlist with json data in jquery?

try this one its worked for me

_x000D_
_x000D_
$(document).ready(function(e){_x000D_
        $.ajax({_x000D_
           url:"fetch",_x000D_
           processData: false,_x000D_
           dataType:"json",_x000D_
           type: 'POST',_x000D_
           cache: false,_x000D_
           success: function (data, textStatus, jqXHR) {_x000D_
                        _x000D_
                         $.each(data.Table,function(i,tweet){_x000D_
      $("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
   });}_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

How to set input type date's default value to today?

If you're doing anything related to date and time in the brower, you want to use Moment.js:

moment().format('YYYY-MM-DD');

moment() returns an object representing the current date and time. You then call its .format() method to get a string representation according to the specified format. In this case, YYYY-MM-DD.

Full example:

<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>

Method to Add new or update existing item in Dictionary

Old question but i feel i should add the following, even more because .net 4.0 had already launched at the time the question was written.

Starting with .net 4.0 there is the namespace System.Collections.Concurrent which includes collections that are thread-safe.

The collection System.Collections.Concurrent.ConcurrentDictionary<> does exactly what you want. It has the AddOrUpdate() method with the added advantage of being thread-safe.

If you're in a high-performance scenario and not handling multiple threads the already given answers of map[key] = value are faster.

In most scenarios this performance benefit is insignificant. If so i'd advise to use the ConcurrentDictionary because:

  1. It is in the framework - It is more tested and you are not the one who has to maintain the code
  2. It is scalable: if you switch to multithreading your code is already prepared for it

How to have the formatter wrap code with IntelliJ?

In order to wrap text in the code editor in IntelliJ IDEA 2020.1 community follow these steps:

Ctrl + Shift + "A" OR Help -> Find Action
Enter: "wrap" into the text box
Toggle: View | Active Editor Soft-Wrap "ON"

enter image description here

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

CMD what does /im (taskkill)?

See the doc : it will close all running tasks using the executable file something.exe, more or less like linux' killall

How to test my servlet using JUnit

EDIT: Cactus is now a dead project: http://attic.apache.org/projects/jakarta-cactus.html


You may want to look at cactus.

http://jakarta.apache.org/cactus/

Project Description

Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...).

The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it.

Cactus implements an in-container strategy, meaning that tests are executed inside the container.

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:

echojson_encode($row);

Importing a long list of constants to a Python file

As an alternative to using the import approach described in several answers, have a look a the configparser module.

The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

How can I mix LaTeX in with Markdown?

you should look at multimarkdown http://fletcherpenney.net/multimarkdown/

it has support for metadata (headers, keywords, date, author, etc), tables, asciimath, mathml, hell i'm sure you could stick latex math code right in there. it's basically an extension to markdown to add all these other very useful features. It uses XSLT, so you can easily whip up your own LaTeX styles, and have it directly convert. I use it all the time, and I like it a lot.

I wish the markdown would just incorporate multimarkdown. it would be rather nice.

Edit: Multimarkdown will produce html, latex, and a few other formats. html can come with a style sheet of your choice. it will convert into MathML as well, which displays in Firefox and Safari/Chrome, if I remember correctly.

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a ToXML() method on every class that is essentially just a Data Transfer Object.

I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.

Here's a couple of examples that Google returned:

XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf

How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx

Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

Get value from a string after a special character

You can use .indexOf() and .substr() like this:

var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)

You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:

var myString = $("input").val().split("?").pop();

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

Resize Google Maps marker icon image

A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.

A 500x500 image will appear larger on the map than a 50x50 image.

No programming required.

Why does Lua have no "continue" statement?

You can wrap loop body in additional repeat until true and then use do break end inside for effect of continue. Naturally, you'll need to set up additional flags if you also intend to really break out of loop as well.

This will loop 5 times, printing 1, 2, and 3 each time.

for idx = 1, 5 do
    repeat
        print(1)
        print(2)
        print(3)
        do break end -- goes to next iteration of for
        print(4)
        print(5)
    until true
end

This construction even translates to literal one opcode JMP in Lua bytecode!

$ luac -l continue.lua 

main <continue.lua:0,0> (22 instructions, 88 bytes at 0x23c9530)
0+ params, 6 slots, 0 upvalues, 4 locals, 6 constants, 0 functions
    1   [1] LOADK       0 -1    ; 1
    2   [1] LOADK       1 -2    ; 3
    3   [1] LOADK       2 -1    ; 1
    4   [1] FORPREP     0 16    ; to 21
    5   [3] GETGLOBAL   4 -3    ; print
    6   [3] LOADK       5 -1    ; 1
    7   [3] CALL        4 2 1
    8   [4] GETGLOBAL   4 -3    ; print
    9   [4] LOADK       5 -4    ; 2
    10  [4] CALL        4 2 1
    11  [5] GETGLOBAL   4 -3    ; print
    12  [5] LOADK       5 -2    ; 3
    13  [5] CALL        4 2 1
    14  [6] JMP         6   ; to 21 -- Here it is! If you remove do break end from code, result will only differ by this single line.
    15  [7] GETGLOBAL   4 -3    ; print
    16  [7] LOADK       5 -5    ; 4
    17  [7] CALL        4 2 1
    18  [8] GETGLOBAL   4 -3    ; print
    19  [8] LOADK       5 -6    ; 5
    20  [8] CALL        4 2 1
    21  [1] FORLOOP     0 -17   ; to 5
    22  [10]    RETURN      0 1

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It causes the error when you access $(this).val() when it called by change event this points to the invoker i.e. CourseSelect so it is working and and will get the value of CourseSelect. but when you manually call it this points to document. so either you will have to pass the CourseSelect object or access directly like $("#CourseSelect").val() instead of $(this).val().

Git diff says subproject is dirty

A submodule may be marked as dirty if filemode settings is enabled and you changed file permissions in submodule subtree.

To disable filemode in a submodule, you can edit /.git/modules/path/to/your/submodule/config and add

[core]
  filemode = false

If you want to ignore all dirty states, you can either set ignore = dirty property in /.gitmodules file, but I think it's better to only disable filemode.

How can I solve a connection pool problem between ASP.NET and SQL Server?

I was facing the same problem, after hours of research I realized I was connected on Guest network without VPN so setting up VPN did the trick for me

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

Building on Demircan Celebi's solution; I wanted the tab to open when modifying the url and open tab without having to reload the page from the server.

<script type="text/javascript">
    $(function() {
        openTabHash(); // for the initial page load
        window.addEventListener("hashchange", openTabHash, false); // for later changes to url
    });


    function openTabHash()
    {
        console.log('openTabHash');
        // Javascript to enable link to tab
        var url = document.location.toString();
        if (url.match('#')) {
            $('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
        } 

        // With HTML5 history API, we can easily prevent scrolling!
        $('.nav-tabs a').on('shown.bs.tab', function (e) {
            if(history.pushState) {
                history.pushState(null, null, e.target.hash); 
            } else {
                window.location.hash = e.target.hash; //Polyfill for old browsers
            }
        })
    }
</script>

How to use executeReader() method to retrieve the value of just one cell

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
    cmd.Parameters.AddWithValue("@id", index);
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
        }
    }
}

Java Switch Statement - Is "or"/"and" possible?

The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.

// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
  // handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
  // handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
  // handle digit case
} else {
  // handle consonant case, assuming other characters are not possible
}

Of course, if this gets any more complicated, I'd recommend a regex matcher.

How to add List<> to a List<> in asp.net

Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));

How to restart kubernetes nodes?

You can delete the node from the master by issuing:

kubectl delete node hostname.company.net

The NOTReady status probably means that the master can't access the kubelet service. Check if everything is OK on the client.

Getting the textarea value of a ckeditor textarea with javascript

Simply execute

CKEDITOR.instances[elementId].getData();

with element id = id of element assigned the editor.

How to get city name from latitude and longitude coordinates in Google Maps?

Try this

  List<Address> list = geoCoder.getFromLocation(location
            .getLatitude(), location.getLongitude(), 1);
    if (list != null & list.size() > 0) {
        Address address = list.get(0);
        result = address.getLocality();
        return result;

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option:

curl_setopt($curlhandle, CURLOPT_VERBOSE, true);

When CURLOPT_VERBOSE is set, output is written to STDERR or the file specified using CURLOPT_STDERR. The output is very informative.

You can also use tcpdump or wireshark to watch the network traffic.

Android design support library for API 28 (P) not working

I've used that option:

With Android Studio 3.2 and higher, you can quickly migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

https://developer.android.com/jetpack/androidx/migrate

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

One line code to detect the browser.

If the browser is IE or Edge, It will return true;

let isIE = /edge|msie\s|trident\//i.test(window.navigator.userAgent)

Java time-based map/cache with expiring keys

Google collections (guava) has the MapMaker in which you can set time limit(for expiration) and you can use soft or weak reference as you choose using a factory method to create instances of your choice.

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

If a folder does not exist, create it

string root = @"C:\Temp";

string subdir = @"C:\Temp\Mahesh";

// If directory does not exist, create it.

if (!Directory.Exists(root))
{

Directory.CreateDirectory(root);

}

The CreateDirectory is also used to create a sub directory. All you have to do is to specify the path of the directory in which this subdirectory will be created in. The following code snippet creates a Mahesh subdirectory in C:\Temp directory.

// Create sub directory

if (!Directory.Exists(subdir))
{

Directory.CreateDirectory(subdir);

}

Installation error: INSTALL_FAILED_OLDER_SDK

I tried all the responses described here but my solution was changing inside my build.gradle file minSdkVersion from 8 to 9 because some libraries in my project can´t work with API 8, that´s was the reason for the message INSTALL_FAILED_OLDER_SDK:

apply plugin: 'com.android.application'

    android {
        compileSdkVersion 22
        buildToolsVersion "22.0.1"

        defaultConfig {
            applicationId "com.tuna.hello.androidstudioapplication"
            minSdkVersion 9
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
        }
...
...
...

Kotlin: How to get and set a text to TextView in Android using Kotlin?

import kotlinx.android.synthetic.main.MainActivity.*

class Mainactivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.MainActivity)

        txt.setText("hello Kotlin")

    }

}

Should I use int or Int32

int is the C# language's shortcut for System.Int32

Whilst this does mean that Microsoft could change this mapping, a post on FogCreek's discussions stated [source]

"On the 64 bit issue -- Microsoft is indeed working on a 64-bit version of the .NET Framework but I'm pretty sure int will NOT map to 64 bit on that system.

Reasons:

1. The C# ECMA standard specifically says that int is 32 bit and long is 64 bit.

2. Microsoft introduced additional properties & methods in Framework version 1.1 that return long values instead of int values, such as Array.GetLongLength in addition to Array.GetLength.

So I think it's safe to say that all built-in C# types will keep their current mapping."

What do pty and tty mean?

A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.

A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.

For example, when you ssh in to a machine and run ls, the ls command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.

Regular expression for exact match of a string

A more straight forward way is to check for equality

if string1 == string2
  puts "match"
else
  puts "not match"
end

however, if you really want to stick to regular expression,

string1 =~ /^123456$/

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

FWIW, on Ubuntu 10.04.2 LTS installing the ca-certificates-java and the ca-certificates packages fixed this problem for me.

How to save all console output to file in R?

To save text from the console: run the analysis and then choose (Windows) "File>Save to File".

Android Get Current timestamp?

This code is Kotlin version. I have another idea to add a random shuffle integer in last digit for giving variance epoch time.

Kotlin version

val randomVariance = (0..100).shuffled().first()
val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance

val deltaEpoch = oldEpoch - currentEpoch

I think it will be better using this kode then depend on android version 26 or more

Android - implementing startForeground for a service?

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground.

If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground.

Once the service has been created, the service must call its startForeground() method within five seconds.

How to drop all tables from the database with manage.py CLI in Django?

Here's a shell script I ended up piecing together to deal with this issue. Hope it saves someone some time.

#!/bin/sh

drop() {
    echo "Droping all tables prefixed with $1_."
    echo
    echo "show tables" | ./manage.py dbshell |
    egrep "^$1_" | xargs -I "@@" echo "DROP TABLE @@;" |
    ./manage.py dbshell
    echo "Tables dropped."
    echo
}

cancel() {
    echo "Cancelling Table Drop."
    echo
}

if [ -z "$1" ]; then
    echo "Please specify a table prefix to drop."
else
    echo "Drop all tables with $1_ prefix?"
    select choice in drop cancel;do
        $choice $1
        break
    done
fi

How to use vagrant in a proxy environment?

If you actually do want your proxy configurations and plugin installations to be in your Vagrantfile, for example if you're making a Vagrantfile just for your corporate environment and can't have users editing environment variables, this was the answer for me:

ENV['http_proxy']  = 'http://proxyhost:proxyport'
ENV['https_proxy'] = 'http://proxyhost:proxyport'

# Plugin installation procedure from http://stackoverflow.com/a/28801317
required_plugins = %w(vagrant-proxyconf)

plugins_to_install = required_plugins.select { |plugin| not Vagrant.has_plugin? plugin }
if not plugins_to_install.empty?
  puts "Installing plugins: #{plugins_to_install.join(' ')}"
  if system "vagrant plugin install #{plugins_to_install.join(' ')}"
    exec "vagrant #{ARGV.join(' ')}"
  else
    abort "Installation of one or more plugins has failed. Aborting."
  end
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.proxy.http     = "#{ENV['http_proxy']}"
  config.proxy.https    = "#{ENV['https_proxy']}"
  config.proxy.no_proxy = "localhost,127.0.0.1"
  # and so on

(If you don't, just set them as environment variables like the other answers say and refer to them from env in config.proxy.http(s) directives.)

How can I put strings in an array, split by new line?

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);

foreach ($arr as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

true array:

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);

$array = array(); // inisiasi variable array in format array

foreach ($arr as $line) { // loop line by line and convert into array
    $array[] = $line;
};

print_r($array); // display all value

echo $array[1]; // diplay index 1

Embed Online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/vE1gst" ></iframe>
_x000D_
_x000D_
_x000D_

Mathematical functions in Swift

As other noted you have several options. If you want only mathematical functions. You can import only Darwin.

import Darwin

If you want mathematical functions and other standard classes and functions. You can import Foundation.

import Foundation

If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.

For OS X, you need import Cocoa.

import Cocoa

For iOS, you need import UIKit.

import UIKit

You can easily discover your playground platform by opening File Inspector (??1).

Playground Settings - Platform

bootstrap 3 tabs not working properly

This will work

$(".nav-tabs a").click(function(){
     $(this).tab('show');
 });

How to split a long array into smaller arrays, with JavaScript

I would like to share my solution as well. It's a little bit more verbose but works as well.

var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var chunksize = 4;


var chunks = [];

data.forEach((item)=>{
  if(!chunks.length || chunks[chunks.length-1].length == chunksize)
  chunks.push([]);

  chunks[chunks.length-1].push(item);
});

console.log(chunks);

Output (formatted):

[ [ 1,  2,  3,  4],
  [ 5,  6,  7,  8],
  [ 9, 10, 11, 12],
  [13, 14, 15    ] ]

How to sign an android apk file

Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:

  1. Export the unsigned package:

Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)

Sign the application using your keystore and the jarsigner tool (follow below steps):

Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"

Now enter belwo command in cmd:

jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias

It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:

jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk

It should come back with: jar verified.

Method 2

If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.

  • File > Export.
  • Export android application
  • Browse-->select your project
  • Next-->Next

These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.

How do I manage MongoDB connections in a Node.js web application?

Manage mongo connection pools in a single self contained module. This approach provides two benefits. Firstly it keeps your code modular and easier to test. Secondly your not forced to mix your database connection up in your request object which is NOT the place for a database connection object. (Given the nature of JavaScript I would consider it highly dangerous to mix in anything to an object constructed by library code). So with that you only need to Consider a module that exports two methods. connect = () => Promise and get = () => dbConnectionObject.

With such a module you can firstly connect to the database

// runs in boot.js or what ever file your application starts with
const db = require('./myAwesomeDbModule');
db.connect()
    .then(() => console.log('database connected'))
    .then(() => bootMyApplication())
    .catch((e) => {
        console.error(e);
        // Always hard exit on a database connection error
        process.exit(1);
    });

When in flight your app can simply call get() when it needs a DB connection.

const db = require('./myAwesomeDbModule');
db.get().find(...)... // I have excluded code here to keep the example  simple

If you set up your db module in the same way as the following not only will you have a way to ensure that your application will not boot unless you have a database connection you also have a global way of accessing your database connection pool that will error if you have not got a connection.

// myAwesomeDbModule.js
let connection = null;

module.exports.connect = () => new Promise((resolve, reject) => {
    MongoClient.connect(url, option, function(err, db) {
        if (err) { reject(err); return; };
        resolve(db);
        connection = db;
    });
});

module.exports.get = () => {
    if(!connection) {
        throw new Error('Call connect first!');
    }

    return connection;
}

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

Regex for Comma delimited list

It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.

([1-9][0-9]*,[ ])*[1-9][0-9]*

Here's how I built that mentally:

[0-9]  any digit.
[1-9][0-9]*  leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ]  as above, followed by a space
([1-9][0-9]*[ ])*  as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]*  as above, with a final number that doesn't have a comma.

How to set component default props on React component

If you're using a functional component, you can define defaults in the destructuring assignment, like so:

export default ({ children, id="menu", side="left", image={menu} }) => {
  ...
};

What are "res" and "req" parameters in Express functions?

req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

Those parameters can be named anything. You could change that code to this if it's more clear:

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

Edit:

Say you have this method:

app.get('/people.json', function(request, response) { });

The request will be an object with properties like these (just to name a few):

  • request.url, which will be "/people.json" when this particular action is triggered
  • request.method, which will be "GET" in this case, hence the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
  • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

To respond to that request, you use the response object to build your response. To expand on the people.json example:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Alternative to deprecated getCellType

You can use:

cell.getCellTypeEnum()

Further to compare the cell type, you have to use CellType as follows:-

if(cell.getCellTypeEnum() == CellType.STRING){
      .
      .
      .
}

You can Refer to the documentation. Its pretty helpful:-

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html

How to make RatingBar to show five stars

<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RatingBar
        android:id="@+id/ruleRatingBar"
        android:isIndicator="true"
        android:numStars="5"
        android:stepSize="0.5"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

How to show a confirm message before delete?

improving on user1697128 (because I cant yet comment on it)

<script>
    function ConfirmDelete()
    {
      var x = confirm("Are you sure you want to delete?");
      if (x)
          return true;
      else
        return false;
    }
</script>    

<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

will cancel form submission if cancel is pressed

Insert Data Into Temp Table with Query

SELECT *
INTO #Temp
FROM

  (SELECT
     Received,
     Total,
     Answer,
     (CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
   FROM
     FirstTable
   WHERE
     Recieved = 1 AND
     application = 'MORESTUFF'
   GROUP BY
     CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
  application LIKE
    isNull(
      '%MORESTUFF%',
      '%')

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

Load image from url

Try this add picasso lib jar file

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).noFade().into(imageView);

What is the difference between readonly="true" & readonly="readonly"?

Giving an element the attribute readonly will give that element the readonly status. It doesn't matter what value you put after it or if you put any value after it, it will still see it as readonly. Putting readonly="false" won't work.

Suggested is to use the W3C standard, which is readonly="readonly".

How to upload & Save Files with Desired name

Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On 

Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above: Make sure that the form uses method="post" The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice: The type="file" attribute of the tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next.

Create The Upload File PHP Script

The "upload.php" file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

How to remove leading zeros from alphanumeric text?

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

s.replaceFirst("^0+(?!$)", "")

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

Test harness:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

See also

Draw radius around a point in Google map

Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances).

// Create marker 
var marker = new google.maps.Marker({
  map: map,
  position: new google.maps.LatLng(53, -2.5),
  title: 'Some location'
});

// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
  map: map,
  radius: 16093,    // 10 miles in metres
  fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');

You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc (full API).

See more source code and example screenshots.

How do I create a file AND any folders, if the folders don't exist?

You want Directory.CreateDirectory()

Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:

using System.IO;

public class copyTemplateFiles
{


public static bool Copy(string Source, string destination)
{

    try {

        string[] Files = null;

        if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
            destination += Path.DirectorySeparatorChar;
        }

        if (!Directory.Exists(destination)) {
            Directory.CreateDirectory(destination);
        }

        Files = Directory.GetFileSystemEntries(Source);
        foreach (string Element in Files) {
            // Sub directories
            if (Directory.Exists(Element)) {
                copyDirectory(Element, destination + Path.GetFileName(Element));
            } else {
                // Files in directory
                File.Copy(Element, destination + Path.GetFileName(Element), true);
            }
        }

    } catch (Exception ex) {
        return false;
    }

    return true;

}



private static void copyDirectory(string Source, string destination)
{
    string[] Files = null;

    if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
        destination += Path.DirectorySeparatorChar;
    }

    if (!Directory.Exists(destination)) {
        Directory.CreateDirectory(destination);
    }

    Files = Directory.GetFileSystemEntries(Source);
    foreach (string Element in Files) {
        // Sub directories
        if (Directory.Exists(Element)) {
            copyDirectory(Element, destination + Path.GetFileName(Element));
        } else {
            // Files in directory
            File.Copy(Element, destination + Path.GetFileName(Element), true);
        }
    }

}

}

mssql '5 (Access is denied.)' error during restoring database

In my case I had to check the box in Overwrite the existing database (WITH REPLACE) under Options tab on Restore Database page.

The reason I was getting this error: because there was already an MDF file present for the database and it was not getting overwritten.

Hope this will help someone.

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

$watch an object

Little performance tip if somebody has a datastore kind of service with key -> value pairs:

If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.

app.factory('dataStore', function () {

    var store = { data: [], change: [] };

    // when storing the data, updating the timestamp
    store.setData = function(key, data){
        store.data[key] = data;
        store.setChange(key);
    }

    // get the change to watch
    store.getChange = function(key){
        return store.change[key];
    }

    // set the change
    store.setChange = function(key){
        store.change[key] = new Date().getTime();
    }

});

And in a directive you are only watching the timestamp to change

app.directive("myDir", function ($scope, dataStore) {
    $scope.dataStore = dataStore;
    $scope.$watch('dataStore.getChange("myKey")', function(newVal, oldVal){
        if(newVal !== oldVal && newVal){
            // Data changed
        }
    });
});

How to make Bootstrap carousel slider use mobile left/right swipe

If you don't want to use jQuery mobile as like me. You can use Hammer.js

It's mostly like jQuery Mobile without unnecessary code.

$(document).ready(function() {
  Hammer(myCarousel).on("swipeleft", function(){
    $(this).carousel('next');
  });
  Hammer(myCarousel).on("swiperight", function(){
    $(this).carousel('prev');
  });
});

How to remove carriage returns and new lines in Postgresql?

In the case you need to remove line breaks from the begin or end of the string, you may use this:

UPDATE table 
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );

Have in mind that the hat ^ means the begin of the string and the dollar sign $ means the end of the string.

Hope it help someone.

Why do some functions have underscores "__" before and after the function name?

Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".

How to convert datatype:object to float64 in python?

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

Enum ToString with user friendly strings

Maybe I'm missing something, but what's wrong with Enum.GetName?

public string GetName(PublishStatusses value)
{
    return Enum.GetName(typeof(PublishStatusses), value)
}

edit: for user-friendly strings, you need to go through a .resource to get internationalisation/localisation done, and it would arguably be better to use a fixed key based on the enum key than a decorator attribute on the same.

Splitting a table cell into two columns in HTML

Please try this way.

<table border="1">
    <tr>
        <th scope="col">Header</th>
        <th scope="col">Header</th>
        <th colspan="2">Header</th>
    </tr> 
    <tr>
        <td scope="row">&nbsp;</td>
        <td scope="row">&nbsp;</td>
        <td scope="col">Split this one</td>
        <td scope="col">into two columns</td>
    </tr>
</table>

SQL: How to properly check if a record exists

The other answers are quite good, but it would also be useful to add LIMIT 1 (or the equivalent, to prevent the checking of unnecessary rows.

Percentage width in a RelativeLayout

You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.

Subclass of RelativeLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with "Percent" suffix.

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
  <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_widthPercent="50%"
      app:layout_heightPercent="50%"
      app:layout_marginTopPercent="25%"
      app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

To use, you need to add this library to your Gradle dependency list:

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

Fixed Table Cell Width

I had one long table td cell, this forced the table to the edges of the browser and looked ugly. I just wanted that column to be fixed size only and break the words when it reaches the specified width. So this worked well for me:

<td><div style='width: 150px;'>Text to break here</div></td>

You don't need to specify any kind of style to table, tr elements. You may also use overflow:hidden; as suggested by other answers but it causes for the excess text to disappear.

Month name as a string

As simple as this

mCalendar = Calendar.getInstance();    
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

Calendar.LONG is to get the full name of the month and Calendar.SHORT gives the name in short. For eg: Calendar.LONG will return January Calendar.SHORT will return Jan

How to increase heap size for jBoss server

Edit the following entry in the run.conf file. But if you have multiple JVMs running on the same JBoss, you might want to run it via command line argument of -Xms2g -Xmx4g (or whatever your preferred start/max memory settings are.

if [ "x$JAVA_OPTS" = "x" ]; then
    JAVA_OPTS="-Xms2g -Xmx4g -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true

get original element from ng-click

You need $event.currentTarget instead of $event.target.

How to use _CRT_SECURE_NO_WARNINGS

Visual Studio 2019 with CMake

Add the following to CMakeLists.txt:

add_definitions(-D_CRT_SECURE_NO_WARNINGS)

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.

series1.csv

1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5

series2.csv

1,56
2,34
3,12
4,26

Source Code

public class CSVChartRows {

  public static void main(String[] args) throws Exception {

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();
  }
}

Resulting Plot

enter image description here

How do I import other TypeScript files?

import {className} from 'filePath';

remember also. The class you are importing , that must be exported in the .ts file.

Android 'Unable to add window -- token null is not for an application' exception

Hello there if you are using adapter there might be a chance.
All you need to know when you used any dialog in adapter,getContext(),context or activity won't work sometime.

Here is the trick I used v.getRootView().getContext() where v is the view object you are referencing.
Eg.


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new DatePickerDialog(v.getRootView().getContext(), date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });  
If you are getting this problem because of alert dialog.
Refer [here][1] But it is same concept.


  [1]: https://stackoverflow.com/questions/6367771/displaying-alertdialog-inside-a-custom-listadapter-class

When is del useful in Python?

Force closing a file after using numpy.load:

A niche usage perhaps but I found it useful when using numpy.load to read a file. Every once in a while I would update the file and need to copy a file with the same name to the directory.

I used del to release the file and allow me to copy in the new file.

Note I want to avoid the with context manager as I was playing around with plots on the command line and didn't want to be pressing tab a lot!

See this question.

Java: how to use UrlConnection to post request with authorization?

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

What are the differences in die() and exit() in PHP?

Here is something that's pretty interesting. Although exit() and die() are equivalent, die() closes the connection. exit() doesn't close the connection.

die():

<?php
    header('HTTP/1.1 304 Not Modified');
    die();
?>

exit():

<?php
    header('HTTP/1.1 304 Not Modified');
    exit();
?>

Results:

exit():

HTTP/1.1 304 Not Modified 
Connection: Keep-Alive 
Keep-Alive: timeout=5, max=100

die():

HTTP/1.1 304 Not Modified 
Connection: close

Just incase in need to take this into account for your project.

Credits: https://stackoverflow.com/a/20932511/4357238

Find the max of 3 numbers in Java with different data types

I have a very simple idea:

 int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.

Regards, Norbert

.substring error: "is not a function"

document.location is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.

Shortcut for solution: document.location.toString().substring(2,3);

Or use document.location.href or window.location.href

What does "fatal: bad revision" mean?

git revert doesn't take a filename parameter. Do you want git checkout?

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

Reading and displaying data from a .txt file

If your file is strictly text, I prefer to use the java.util.Scanner class.

You can create a Scanner out of a file by:

Scanner fileIn = new Scanner(new File(thePathToYourFile));

Then, you can read text from the file using the methods:

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file

And, you can check if there is any more text left with:

fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file

Once you have read the text, and saved it into a String, you can print the string to the command line with:

System.out.print(aString);
System.out.println(aString);

The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.

Bootstrap: change background color

You can target that div from your stylesheet in a number of ways.

Simply use

.col-md-6:first-child {
  background-color: blue;
}

Another way is to assign a class to one div and then apply the style to that class.

<div class="col-md-6 blue"></div>

.blue {
  background-color: blue;
}

There are also inline styles.

<div class="col-md-6" style="background-color: blue"></div>

Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

_x000D_
_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
    <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
      <div class="col-xs-6">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
      <div class="col-xs-6 blue">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

What is the difference between & vs @ and = in angularJS

@: one-way binding

=: two-way binding

&: function binding

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

UITableView Cell selected Color?

Swift 4+:

Add following lines in your table cell

let bgColorView = UIView()
bgColorView.backgroundColor =  .red
self.selectedBackgroundView = bgColorView

Finally it should be as below

override func setSelected(_ selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        let bgColorView = UIView()
        bgColorView.backgroundColor =  .red
        self.selectedBackgroundView = bgColorView

    }

CSS Background Image Not Displaying

According to your CSS file path, I will suppose it is at the same directory with your HTML page, you have to change the url as follows:

body { background: url(img/debut_dark.png) repeat 0 0; }

Laravel-5 how to populate select box from database with id value and name value

I have added toArray() after pluck

$items = Item::get()->pluck('name', 'id')->toArray();

{{ Form::select('item_id', [null=>'Please Select'] + $items) }}

Command prompt won't change directory to another drive

If you want to change from current working directory to another directory then in the command prompt you need to type the name of the drive you need to change to, followed by : symbol. example: assume that you want to change to D-drive and you are in C-drive currently, then type D: and hit Enter.

On the other hand if you wish to change directory within same working directory then use cd(change directory) command followed by directory name. example: assuming you wish to change to new folder then type: cd "new folder" and hit enter.

Tips to use CMD: Windows command line are not case sensitive. When working with a file or directory with a space, surround it in quotes. For example, My Documents would be "My Documents". When a file or directory is deleted in the command line, it is not moved into the Recycle bin. If you need help with any of command type /? after the command. For example, dir /? would give the options available for the dir command.

What is the meaning of "$" sign in JavaScript

Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).

There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier.

JavaScript allows upper and lower letters, numbers, and $ and _. The $ was intended to be used for machine-generated variables (such as $0001).

Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.

IOS 7 Navigation Bar text and arrow color

Swift 5/iOS 13

To change color of title in controller:

UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Getting "cannot find Symbol" in Java project in Intellij

recompiling the main Application.java class did it for me, right click on class > Recompile

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

How to suppress "unused parameter" warnings in C?

A gcc/g++ specific way to suppress the unused parameter warning for a block of source code is to enclose it with the following pragma statements:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
<code with unused parameters here>
#pragma GCC diagnostic pop

How can I add some small utility functions to my AngularJS application?

You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.

function doSomething( a, b ) {
    return a + b;
};

angular.module('moduleName',[])
    // Define
    .constant('$doSomething', doSomething)
    // Usage
    .controller( 'SomeController', function( $doSomething ) {
        $scope.added = $doSomething( 100, 200 );
    })
;

Python find elements in one list that are not in the other

I would zip the lists together to compare them element by element.

main_list = [b for a, b in zip(list1, list2) if a!= b]

How can strip whitespaces in PHP's variable?

The \s regex argument is not compatible with UTF-8 multybyte strings.

This PHP RegEx is one I wrote to solve this using PCRE (Perl Compatible Regular Expressions) based arguments as a replacement for UTF-8 strings:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

- Example Usage -

Before:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

After:

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

PCRE Argument Listing

Source: https://www.rexegg.com/regex-quickstart.html

Character   Legend  Example Sample Match
\t  Tab T\t\w{2}    T     ab
\r  Carriage return character   see below   
\n  Line feed character see below   
\r\n    Line separator on Windows   AB\r\nCD    AB
    CD
\N  Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h  Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator      
\H  One character that is not a horizontal whitespace       
\v  .NET, JavaScript, Python, Ruby: vertical tab        
\v  Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator      
\V  Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace      
\R  Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)      

Repeat table headers in print mode

Chrome and Opera browsers do not support thead {display: table-header-group;} but rest of others support properly..

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

JSON datetime between Python and JavaScript

I've worked it out.

Let's say you have a Python datetime object, d, created with datetime.now(). Its value is:

datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)

You can serialize it to JSON as an ISO 8601 datetime string:

import json    
json.dumps(d.isoformat())

The example datetime object would be serialized as:

'"2011-05-25T13:34:05.787000"'

This value, once received in the Javascript layer, can construct a Date object:

var d = new Date("2011-05-25T13:34:05.787000");

As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:

d.toJSON()

Which would give you:

'2011-05-25T20:34:05.787Z'

This string, once received in Python, could be deserialized back to a datetime object:

datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')

This results in the following datetime object, which is the same one you started with and therefore correct:

datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

process.waitFor() never returns

There are many reasons that waitFor() doesn't return.

But it usually boils down to the fact that the executed command doesn't quit.

This, again, can have many reasons.

One common reason is that the process produces some output and you don't read from the appropriate streams. This means that the process is blocked as soon as the buffer is full and waits for your process to continue reading. Your process in turn waits for the other process to finish (which it won't because it waits for your process, ...). This is a classical deadlock situation.

You need to continually read from the processes input stream to ensure that it doesn't block.

There's a nice article that explains all the pitfalls of Runtime.exec() and shows ways around them called "When Runtime.exec() won't" (yes, the article is from 2000, but the content still applies!)

How to enumerate an enum

public void PrintAllSuits()
{
    foreach(string suit in Enum.GetNames(typeof(Suits)))
    {
        Console.WriteLine(suit);
    }
}

How would I get a cron job to run every 30 minutes?

crontab does not understand "intervals", it only understands "schedule"

valid hours: 0-23 -- valid minutes: 0-59

example #1

30 * * * * your_command

this means "run when the minute of each hour is 30" (would run at: 1:30, 2:30, 3:30, etc)

example #2

*/30 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

example #3

0,30 * * * * your_command

this means "run when the minute of each hour is 0 or 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

it's another way to accomplish the same results as example #2

example #4

19 * * * * your_command

this means "run when the minute of each hour is 19" (would run at: 1:19, 2:19, 3:19, etc)

example #5

*/19 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 19" (would run at: 1:19, 1:38, 1:57, 2:19, 2:38, 2:57 etc)

note: several refinements have been made to this post by various users including the author

Cycles in an Undirected Graph

I believe using DFS correctly also depends on how are you going to represent your graph in the code. For example suppose you are using adjacent lists to keep track of neighbor nodes and your graph has 2 vertices and only one edge: V={1,2} and E={(1,2)}. In this case starting from vertex 1, DFS will mark it as VISITED and will put 2 in the queue. After that it will pop vertex 2 and since 1 is adjacent to 2, and 1 is VISITED, DFS will conclude that there is a cycle (which is wrong). In other words in Undirected graphs (1,2) and (2,1) are the same edge and you should code in a way for DFS not to consider them different edges. Keeping parent node for each visited node will help to handle this situation.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

It was because of docker which uses hyper-v. You just have to remove hyper-v from windows features.

How to select into a variable in PL/SQL when the result might be null?

You can simply handle the NO_DATA_FOUND exception by setting your variable to NULL. This way, only one query is required.

    v_column my_table.column%TYPE;

BEGIN

    BEGIN
      select column into v_column from my_table where ...;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        v_column := NULL;
    END;

    ... use v_column here
END;

round() for float in C++

A certain type of rounding is also implemented in Boost:

#include <iostream>

#include <boost/numeric/conversion/converter.hpp>

template<typename T, typename S> T round2(const S& x) {
  typedef boost::numeric::conversion_traits<T, S> Traits;
  typedef boost::numeric::def_overflow_handler OverflowHandler;
  typedef boost::numeric::RoundEven<typename Traits::source_type> Rounder;
  typedef boost::numeric::converter<T, S, Traits, OverflowHandler, Rounder> Converter;
  return Converter::convert(x);
}

int main() {
  std::cout << round2<int, double>(0.1) << ' ' << round2<int, double>(-0.1) << ' ' << round2<int, double>(-0.9) << std::endl;
}

Note that this works only if you do a to-integer conversion.

perform an action on checkbox checked or unchecked event on html form

The currently accepted answer doesn't always work.

(To read about the problem and circumstances, read this: Defined function is "Not defined".)

So, you have 3 options:

1 (it has above-mentioned drawback)

<input type="checkbox" onchange="doAlert(this)">

<script>
function doAlert(checkboxElem) {
    if (checkboxElem.checked) {
        alert ('hi');
    } else {
        alert ('bye');
    }
}
</script>

2 and 3

<input type="checkbox" id="foo">

<script>
function doAlert() {
    var input = document.querySelector('#foo');

    // input.addEventListener('change', function() { ... });
    // or
    // input.onchange = function() { ... };
    input.addEventListener('change', function() {
        if (input.checked) {
            alert ('hi');
        } else {
            alert ('bye');
        }
    });
}

doAlert();
</script>

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

In case you are using Eclipse you might try http4e

How do I create a local database inside of Microsoft SQL Server 2014?

As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx

Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx

What do the result codes in SVN mean?

SVN status columns

$ svn status
L index.html

The output of the command is split into six columns, but that is not obvious because sometimes the columns are empty. Perhaps it would have made more sense to indicate the empty columns with dashes, the way ls -l does, instead of nothing. Then, for example, L index.html would look like --L--- index.html, which makes it obvious the only information we have is in the third column the one about locking. Anyway, once you know that it begins to make more sense.

SVN Status first column: A, D, M, R, C, X, I, ?, !, ~

The first column indicates that an item was added, deleted, or otherwise changed.

      No modifications.

 A    Item is scheduled for Addition.

 D    Item is scheduled for Deletion.

 M    Item has been modified.

 R    Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.

 C    The contents (as opposed to the properties) of the item conflict with updates received from the repository.

 X    Item is related to an externals definition.

 I    Item is being ignored (e.g. with the svn:ignore property).

 ?    Item is not under version control.

 !    Item is missing (e.g. you moved or deleted it without using svn). This also indicates that a directory is incomplete (a checkout or update was interrupted).

 ~    Item is versioned as one kind of object (file, directory, link), but has been replaced by different kind of object.

SVN Status second column: M, C

The second column tells the status of a file’s or directory’s properties.

      No modifications.

 M    Properties for this item have been modified.

 C    Properties for this item are in conflict with property updates received from the repository.

SVN Status third column: L

The third column is populated only if the working copy directory is locked (an svn cleanup should normally be enough to clear it out)

      Item is not locked.

 L    Item is locked.

SVN Status fourth column: +

The fourth column is populated only if the item is scheduled for addition-with-history.

      No history scheduled with commit.

 +    History scheduled with commit.

SVN Status fifth column: S

The fifth column is populated only if the item’s working copy is switched relative to its parent

      Item is a child of its parent directory.

 S    Item is switched.

SVN Status sixth column: K, O, T, B

The sixth column is populated with lock information.

      When –show-updates is used, the file is not locked. If –show-updates is not used, this merely means that the file is not locked in this working copy.

 K    File is locked in this working copy.

 O    File is locked either by another user or in another working copy. This only appears when –show-updates is used.

 T    File was locked in this working copy, but the lock has been stolen and is invalid. The file is currently locked in the repository. This only appears when –show-updates is used.-

 B    File was locked in this working copy, but the lock has been broken and is invalid. The file is no longer locked This only appears when –show-updates is used.

SVN Status seventh column: *

The out-of-date information appears in the seventh column (only if you pass the –show-updates switch). This is something people who are new to SVN expect the command to do, not realizing it only compare the current state of the file with what information it fetched from the server on the last update.

      The item in your working copy is up-to-date.

 *    A newer revision of the item exists on the server.

How does bitshifting work in Java?

Firstly, you can not shift a byte in java, you can only shift an int or a long. So the byte will undergo promotion first, e.g.

00101011 -> 00000000000000000000000000101011

or

11010100 -> 11111111111111111111111111010100

Now, x >> N means (if you view it as a string of binary digits):

  • The rightmost N bits are discarded
  • The leftmost bit is replicated as many times as necessary to pad the result to the original size (32 or 64 bits), e.g.

00000000000000000000000000101011 >> 2 -> 00000000000000000000000000001010

11111111111111111111111111010100 >> 2 -> 11111111111111111111111111110101

What's is the difference between include and extend in use case diagram?

The include relationship allows one use case to include the steps of another use case.

For example, suppose you have an Amazon Account and you want to check on an order, well it is impossible to check on the order without first logging into your account. So the flow of events would like so...

enter image description here

The extend relationship is used to add an extra step to the flow of a use case, that is usually an optional step...

enter image description here

Imagine that we are still talking about your amazon account. Lets assume the base case is Order and the extension use case is Amazon Prime. The user can choose to just order the item regularly, or, the user has the option to select Amazon Prime which ensure his order will arrive faster at higher cost.

However, note that the user does not have to select Amazon Prime, this is just an option, they can choose to ignore this use case.

Get WooCommerce product categories from WordPress

In my opinion this is the simplest solution

$orderby = 'name';
                $order = 'asc';
                $hide_empty = false ;
                $cat_args = array(
                    'orderby'    => $orderby,
                    'order'      => $order,
                    'hide_empty' => $hide_empty,
                );

                $product_categories = get_terms( 'product_cat', $cat_args );

                if( !empty($product_categories) ){
                    echo '

                <ul>';
                    foreach ($product_categories as $key => $category) {
                        echo '

                <li>';
                        echo '<a href="'.get_term_link($category).'" >';
                        echo $category->name;
                        echo '</a>';
                        echo '</li>';
                    }
                    echo '</ul>


                ';
                }

How do I upgrade to Python 3.6 with conda?

Anaconda has not updated python internally to 3.6.

a) Method 1

  1. If you wanted to update you will type conda update python
  2. To update anaconda type conda update anaconda
  3. If you want to upgrade between major python version like 3.5 to 3.6, you'll have to do

    conda install python=$pythonversion$
    

b) Method 2 - Create a new environment (Better Method)

conda create --name py36 python=3.6

c) To get the absolute latest python(3.6.5 at time of writing)

conda create --name py365 python=3.6.5 --channel conda-forge

You can see all this from here

Also, refer to this for force upgrading

EDIT: Anaconda now has a Python 3.6 version here

How to use sudo inside a docker container?

The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.

Here's the TL;DR version:

RUN apt-get update \
 && apt-get install -y sudo

RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

USER docker

# this is where I was running into problems with the other approaches
RUN sudo apt-get update 

I was using FROM node:9.3 for this, but I suspect that other similar container bases would work as well.

How to replace � in a string

As others have said, you posted 3 characters instead of one. I suggest you run this little snippet of code to see what's actually in your string:

public static void dumpString(String text)
{
    for (int i=0; i < text.length(); i++)
    {
        System.out.println("U+" + Integer.toString(text.charAt(i), 16) 
                           + " " + text.charAt(i));
    }
}

If you post the results of that, it'll be easier to work out what's going on. (I haven't bothered padding the string - we can do that by inspection...)

How to deal with missing src/test/java source folder in Android/Maven project?

We can add java folder from

  1. Build Path -> Source.
  2. click on Add Folder.
  3. Select main as the container.
  4. click on Create Folder.
  5. Enter Folder name as java.
  6. Click on Finish

It works fine.

PHP Get URL with Parameter

for complette URL with protocol, servername and parameters:

 $base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .  $_SERVER['HTTP_HOST'];
 $url = $base_url . $_SERVER["REQUEST_URI"];

Why is division in Ruby returning an integer instead of decimal value?

You can check it with irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667

vba error handling in loop

What about?

If oSheet.QueryTables.Count > 0 Then
  oCmbBox.AddItem oSheet.Name
End If 

Or

If oSheet.ListObjects.Count > 0 Then
    '// Source type 3 = xlSrcQuery
    If oSheet.ListObjects(1).SourceType = 3 Then
         oCmbBox.AddItem oSheet.Name
    End IF
End IF

Git diff against a stash

FWIW This may be a bit redundant to all the other answers and is very similar to the accepted answer which is spot on; but maybe it will help someone out.

git stash show --help will give you all you should need; including stash show info.

show [<stash>]

Show the changes recorded in the stash as a diff between the stashed state and its original parent. When no is given, shows the latest one. By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@{1} to view the second most recent stash in patch form). You can use stash.showStat and/or stash.showPatch config variables to change the default behavior.

What is the difference between tree depth and height?

I know it's weird but Leetcode defines depth in terms of number of nodes in the path too. So in such case depth should start from 1 (always count the root) and not 0. In case anybody has the same confusion like me.

How to resolve the "ADB server didn't ACK" error?

For me it didn't work , it was related to a path problem happened after android studio 2.0 preview 1, I needed to update genymotion and virtual box, and apparently they tried to use same port for adb.

Solution is explained here link! Basically you just need to:

1) open genymotion settings

2) specify sdk path for the adb manually

3) adb kill-server

4) adb start-server

How to tell Jackson to ignore a field during serialization if its value is null?

This Will work in Spring boot 2.0.3+ and Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

Find an object in array?

Swift 2 or later

You can combine indexOf and map to write a "find element" function in a single line.

let array = [T(name: "foo"), T(name: "Foo"), T(name: "FOO")]
let foundValue = array.indexOf { $0.name == "Foo" }.map { array[$0] }
print(foundValue) // Prints "T(name: "Foo")"

Using filter + first looks cleaner, but filter evaluates all the elements in the array. indexOf + map looks complicated, but the evaluation stops when the first match in the array is found. Both the approaches have pros and cons.

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

I want to show all tables that have specified column name

select table_name
from information_schema.columns
where COLUMN_NAME = 'MyColumn'

File inside jar is not visible for spring

I had the same issue, ended up using the much more convenient Guava Resources:

Resources.getResource("my.file")