Programs & Examples On #Statsvn

StatSVN is a metrics-analysis tool for charting software evolution through analysis of Subversion source repositories.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

What's the best/easiest GUI Library for Ruby?

Wxruby is a great framework, simple and clean. Try it or use glade with ruby (the simpliest option)

Spring Bean Scopes

Just want to update, that in Spring 5, as mentioned in Spring docs, Spring supports 6 scopes, four of which are available only if you use a web-aware ApplicationContext.

singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype Scopes a single bean definition to any number of object instances.

request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

How do I insert non breaking space character   in a JSF page?

If your using the RichFaces library you can also use the tag rich:spacer which will add an "invisible" image with a given length and height. Usually much easier and prettier than to add tons of nbsp;.

Where you want your space to show you simply add:

<rich:spacer height="1" width="2" />

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

Converting integer to string in Python

Here is a simpler solution:

one = "1"
print(int(one))

Output console

>>> 1

In the above program, int() is used to convert the string representation of an integer.

Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.

In the same way, str() is used to convert an integer to string.

number = 123567
a = []
a.append(str(number))
print(a) 

I used a list to print the output to highlight that variable (a) is a string.

Output console

>>> ["123567"]

But to understand the difference how a list stores a string and integer, view the below code first and then the output.

Code

a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)

Output console

>>> ["This is a string and next is an integer", 23]

How to implement the Android ActionBar back button?

I think onSupportNavigateUp() is simplest and best way to do so

check the code in this link Click here for complete code

Javascript negative number

If you really want to dive into it and even need to distinguish between -0 and 0, here's a way to do it.

function negative(number) {
  return !Object.is(Math.abs(number), +number);
}

console.log(negative(-1));  // true
console.log(negative(1));   // false
console.log(negative(0));   // false
console.log(negative(-0));  // true

How do I compare two strings in python?

This is a pretty basic example, but after the logical comparisons (==) or string1.lower() == string2.lower(), maybe can be useful to try some of the basic metrics of distances between two strings.

You can find examples everywhere related to these or some other metrics, try also the fuzzywuzzy package (https://github.com/seatgeek/fuzzywuzzy).

import Levenshtein
import difflib

print(Levenshtein.ratio('String1', 'String2'))
print(difflib.SequenceMatcher(None, 'String1', 'String2').ratio())

How to write a std::string to a UTF-8 text file

Use Glib::ustring from glibmm.

It is the only widespread UTF-8 string container (AFAIK). While glyph (not byte) based, it has the same method signatures as std::string so the port should be simple search and replace (just make sure that your data is valid UTF-8 before loading it into a ustring).

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

Making authenticated POST requests with Spring RestTemplate for Android

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

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

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

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

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

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

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

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

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

How to Maximize window in chrome using webDriver (python)

Nothing worked for me except:

driver.set_window_size(1024, 600)
driver.maximize_window()

I found this by inspecting selenium/webdriver/remote/webdriver.py. I've never found any useful documentation, but reading the code has been marginally effective.

Iterating through array - java

You can import the lib org.apache.commons.lang.ArrayUtils

There is a static method where you can pass in an int array and a value to check for.

contains(int[] array, int valueToFind) Checks if the value is in the given array.

ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

How to fetch data from local JSON file on react native?

Since React Native 0.4.3 you can read your local JSON file like this:

const customData = require('./customData.json');

and then access customData like a normal JS object.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

If you can update your connector to a version, which supports the new authentication plugin of MySQL 8, then do that. If that is not an option for some reason, change the default authentication method of your database user to native.

Defining Z order of views of RelativeLayout in Android

API 21 has view.setElevation(float) build-in

Use ViewCompat.setElevation(view, float); for backward compatibility

More methods ViewCompat.setZ(v, pixels) and ViewCompat.setTranslationZ(v, pixels)

Another way collect buttons or view array and use addView to add to RelativeLayout

How to get a list of programs running with nohup

You can also just use the top command and your user ID will indicate the jobs running and the their times.

$ top

(this will show all running jobs)

$ top -U [user ID]

(This will show jobs that are specific for the user ID)

What is the best way to update the entity in JPA

It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.

How to invert a grep expression

Add the -v option to your grep command to invert the results.

Get current URL/URI without some of $_GET variables

In Yii2 you can do:

use yii\helpers\Url;
$withoutLg = Url::current(['lg'=>null], true);

More info: https://www.yiiframework.com/doc/api/2.0/yii-helpers-baseurl#current%28%29-detail

How to display UTF-8 characters in phpMyAdmin?

If you're using PDO don't forget to initiate it with UTF8:

 $con = new PDO('mysql:host=' . $server . ';dbname=' . $db . ';charset=UTF8', $user, $pass,  array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

(just spent 5 hours to figure this out, hope it will save someone precious time...)

Can the Unix list command 'ls' output numerical chmod permissions?

it almost can ..

 ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

Calculating distance between two geographic locations

There is only one user Location, so you can iterate List of nearby places can call the distanceTo() function to get the distance, you can store in an array if you like.

From what I understand, distanceBetween() is for far away places, it's output is a WGS84 ellipsoid.

How to remove the last element added into the List?

You can use List<T>.RemoveAt method:

rows.RemoveAt(rows.Count -1);

How do I initialize a TypeScript Object with a JSON-Object?

For simple objects, I like this method:

class Person {
  constructor(
    public id: String, 
    public name: String, 
    public title: String) {};

  static deserialize(input:any): Person {
    return new Person(input.id, input.name, input.title);
  }
}

var person = Person.deserialize({id: 'P123', name: 'Bob', title: 'Mr'});

Leveraging the ability to define properties in the constructor lets it be concise.

This gets you a typed object (vs all the answers that use Object.assign or some variant, which give you an Object) and doesn't require external libraries or decorators.

Persist javascript variables across pages?

For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.

http://www.w3.org/TR/2009/WD-webstorage-20091222/

https://www.w3.org/TR/webstorage/. (second edition)

Here are some sample code for setting and getting the values using sessionStorage and localStorage :

 // HTML5 session Storage
 sessionStorage.setItem("variableName","test");
 sessionStorage.getItem("variableName");


//HTML5 local storage 
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");

TypeError: 'undefined' is not a function (evaluating '$(document)')

You can use both jQuery and $ in below snippet. it worked for me

jQuery( document ).ready(function( $ ) {
  // jQuery(document)
  // $(document)
});

How to increase heap size for jBoss server

I have mentioned the configuration changes needed for the increase of heap size in Windows or Linux environments.

Linux:

bin/standalone.conf

Check for the following line,

JAVA_OPTS

and change it accordingly to suit your heap size needs

-Xms1303m: initial heap size in megabytes
-Xmx1303m: maximum heap size in megabytes

JAVA_OPTS="-Xms1024M -Xmx2048M -XX:MaxPermSize=2048M -XX:MaxHeapSize=2048M"

Windows:

bin/standalone.conf.bat

JAVA_OPTS="-Xms1024M -Xmx2048M -XX:MaxPermSize=2048M -XX:MaxHeapSize=2048M"

Now restart the server and it will work without prompting any heap size errors.

For more information you can refer this link below.

https://access.redhat.com/documentation/en-us/jboss_enterprise_application_platform/5/html/getting_started_guide/adjust_memory_settings

Is it possible to add an array or object to SharedPreferences on Android

So from the android developer site on Data Storage:

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

So I think it is okay since it is simply just key-value pairs which are persisted.

To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:

// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");

SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();

for (String s : nameIcons.keySet()) {
    // use the name as the key, and the icon as the value
    keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()

You would do something similar to read the key-value pairs again. Let me know if this works.

Update: If you're using API level 11 or later, there is a method to write out a String Set

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):

bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
               "~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));

And angular app would appear in bundle unmodified.

How can I run multiple curl requests processed sequentially?

According to the curl man page:

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:

curl http://example.com/?update_=1 http://example.com/?update_=2

Export and Import all MySQL databases at one time

Why parsing formatted output while the mysql command can do directly what you want?

databases=`mysql -u $USER -p$PASSWORD --batch --skip-column-names -e "SHOW DATABASES;" | grep -E -v "(information|performance)_schema"`

Lists the database names and only this.

Experimental decorators warning in TypeScript compilation

In Visual Code Studio Go to File >> Preferences >> Settings, Search "decorator" in search field and Check the option as in image. enter image description here

How to ignore HTML element from tabindex?

The way to do this is by adding tabindex="-1". By adding this to a specific element, it becomes unreachable by the keyboard navigation. There is a great article here that will help you further understand tabindex.

How do you format a Date/Time in TypeScript?

For Angular you should simply use formatDate instead of the DatePipe.

import {formatDate} from '@angular/common';

constructor(@Inject(LOCALE_ID) private locale: string) { 
    this.dateString = formatDate(Date.now(),'yyyy-MM-dd',this.locale);
}

Convert a Unicode string to a string in Python (containing extra symbols)

There is a library that can help with Unicode issues called ftfy. Has made my life easier.

Example 1

import ftfy
print(ftfy.fix_text('ünicode'))

output -->
ünicode

Example 2 - UTF-8

import ftfy
print(ftfy.fix_text('\xe2\x80\xa2'))

output -->
•

Example 3 - Unicode code point

import ftfy
print(ftfy.fix_text(u'\u2026'))

output -->
…

https://ftfy.readthedocs.io/en/latest/

pip install ftfy

https://pypi.org/project/ftfy/

Facebook Graph API error code list

I was looking for the same thing and I just found this list

https://developers.facebook.com/docs/reference/api/errors/

Get Application Directory

Just use this in your code

 context.getApplicationInfo().dataDir

How to measure the a time-span in seconds using System.currentTimeMillis()?

From your code it would appear that you are trying to measure how long a computation took (as opposed to trying to figure out what the current time is).

In that case, you need to call currentTimeMillis before and after the computation, take the difference, and divide the result by 1000 to convert milliseconds to seconds.

How do I clear a search box with an 'x' in bootstrap 3?

AngularJS / UI-Bootstrap Answer

  • Use Bootstrap's has-feedback class to show an icon inside the input field.
  • Make sure the icon has style="cursor: pointer; pointer-events: all;"
  • Use ng-click to clear the text.

JavaScript (app.js)

var app = angular.module('plunker', ['ui.bootstrap']);

app.controller('MainCtrl', function($scope) {

  $scope.params = {};

  $scope.clearText = function() {
    $scope.params.text = null;
  }

});

HTML (index.html snippet)

      <div class="form-group has-feedback">
        <label>text box</label>
        <input type="text"
               ng-model="params.text"
               class="form-control"
               placeholder="type something here...">
        <span ng-if="params.text"
              ng-click="clearText()"
              class="glyphicon glyphicon-remove form-control-feedback" 
              style="cursor: pointer; pointer-events: all;"
              uib-tooltip="clear">
        </span>
      </div>

Here's the plunker: http://plnkr.co/edit/av9VFw?p=preview

How can I change the size of a Bootstrap checkbox?

Or you can style it with pixels.

 .big-checkbox {width: 30px; height: 30px;}

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

How to fix: "HAX is not working and emulator runs in emulation mode"

If you are on a mac you can install haxm using homebrew via cask which is a built-in extension (as of 2015) which allows installing non-open-source and desktop apps (i.e. chrome, firefox, eclipse, etc.):

brew cask install intel-haxm 

Android Studio

If you are using Android Studio then you can achieve the same result from the menu Tools ? SDK Manager, and then on the SDK Tools tab, select the checkbox for Intel x86 Emulator Accelerator (HAXM installer), and click Ok.

JQuery: How to get selected radio button value?

This work for me hope this will help: to get radio selected value you have to use ratio name as selector like this

selectedVal = $('input[name="radio_name"]:checked').val();

selectedVal will have the required value, change the radio_name according to yours, in your case it would b "myradiobutton"

selectedVal = $('input[name="myradiobutton"]:checked').val();

Is there a CSS selector by class prefix?

CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

(looks like it's actually at 'recommendation' status for 2.1 and 3)


Here's an outline of how I *think it works:

  • [ ] : is the container for complex selectors if you will...
  • class : 'class' is the attribute you are looking at in this case.
  • * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.
  • test- : the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)

So, for example:

[class*='test-'] {
  color: red;
}

You could be more specific if you have good reason, with the element too

ul[class*='test-'] > li { ... }

I've tried to find edge cases, but I see no need to use a combination of ^ and * - as * gets everything...

example: http://codepen.io/sheriffderek/pen/MaaBwp

http://caniuse.com/#feat=css-sel2

Everything above IE6 will happily obey. : )

note that:

[class] { ... }

Will select anything with a class...

Read CSV file column by column

You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:

public class ParseCSV {
  public static void main(String[] args) {
    try {
      //csv file containing data
      String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
      CSVReader reader = new CSVReader(new FileReader(strFile));
      String [] nextLine;
      int lineNumber = 0;
      while ((nextLine = reader.readNext()) != null) {
        lineNumber++;
        System.out.println("Line # " + lineNumber);

        // nextLine[] is an array of values from the line
        System.out.println(nextLine[4] + "etc...");
      }
    }
  }
}

How to remove element from an array in JavaScript?

There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).

1) SHIFT() - Remove First Element from Original Array and Return the First Element

See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index

See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.

See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

Python can't find module in the same folder

In my case, Python was unable to find it because I'd put the code inside a module with hyphens, e.g. my-module. When I changed it to my_module it worked.

ArrayList of int array in java

Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.

Iterating Through a Dictionary in Swift

Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

var largest = 0
var whichKind: String? = nil

for (kind, numbers) in interestingNumbers {
    for number in numbers {
    if number > largest {
        whichKind = kind
        largest = number
    }
  }
}

print(whichKind)
print(largest)

OUTPUT:
Optional("Square")
25

How to vertically align into the center of the content of a div with defined width/height?

I found this solution in this article

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

It work like a charm if the height of element is not fixed.

How do I copy directories recursively with gulp?

So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.

One way I solved this problem was by making the beginning of the path relative. For your case:

gulp.src([
    'index.php',
    '*css/**/*',
    '*js/**/*',
    '*src/**/*',
])
.pipe(gulp.dest('/var/www/'));

The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)

This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/ at the same level as js, you would end up matching both.

This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.

What does .class mean in Java?

That means a Class with a type of anything (unknown).

You should read java generics tutorial to get to understand it better

SQL query for a carriage return in a string and ultimately removing carriage return

This also works

SELECT TRANSLATE(STRING_WITH_NL_CR, CHAR(10) || CHAR(13), '  ') FROM DUAL;

How to concatenate strings in twig

Also a little known feature in Twig is string interpolation:

{{ "http://#{app.request.host}" }}

How to get date in BAT file

You get and format like this

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%

Note: Above only works on US locale. It assumes the output of echo %date% looks like this: Thu 02/13/21. If you have different Windows locale settings, you will need to modify the script based on your configuration.

Open firewall port on CentOS 7

To view open ports, use the following command:

firewall-cmd --list-ports

We use the following to see services whose ports are open:

firewall-cmd --list-services

We use the following to see services whose ports are open and see open ports:

firewall-cmd --list-all

To add a service to the firewall, we use the following command, in which case the service will use any port to open in the firewall:

firewall-cmd --add-services=ntp 

For this service to be permanently open we use the following command:

firewall-cmd -add-service=ntp --permanent 

To add a port, use the following command:

firewall-cmd --add-port=132/tcp  --permanent

How to convert timestamp to datetime in MySQL?

You can use

select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;

For in details description about

  1. from_unixtime()
  2. unix_timestamp()

How can I tell how many objects I've stored in an S3 bucket?

The api will return the list in increments of 1000. Check the IsTruncated property to see if there are still more. If there are, you need to make another call and pass the last key that you got as the Marker property on the next call. You would then continue to loop like this until IsTruncated is false.

See this Amazon doc for more info: Iterating Through Multi-Page Results

Get error message if ModelState.IsValid fails?

If you're looking to generate a single error message string that contains the ModelState error messages you can use SelectMany to flatten the errors into a single list:

if (!ModelState.IsValid)
{
    var message = string.Join(" | ", ModelState.Values
        .SelectMany(v => v.Errors)
        .Select(e => e.ErrorMessage));
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}

How to set back button text in Swift

You can do it from interface builder as follows:

click on the navigation item of previous view controller

enter image description here

from the attributes inspector set the back button text to whatever you want. Thats it!!

enter image description here

Force GUI update from UI Thread

After updating the UI, start a task to perform with the long running operation:

label.Text = "Please Wait...";

Task<string> task = Task<string>.Factory.StartNew(() =>
{
    try
    {
        SomewhatLongRunningOperation();
        return "Success!";
    }
    catch (Exception e)
    {
        return "Error: " + e.Message;
    }
});
Task UITask = task.ContinueWith((ret) =>
{
    label.Text = ret.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());

This works in .NET 3.5 and later.

Adding blur effect to background in swift

I have tested this code and it's working fine:

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

For Swift 3.0:

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

For Swift 4.0:

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

Here you can see result:

blurred view

Or you can use this lib for that:

https://github.com/FlexMonkey/Blurable

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.

AJAX Mailchimp signup form integration

You should use the server-side code in order to secure your MailChimp account.

The following is an updated version of this answer which uses PHP:

The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.

1) Download the PHP 5 jQuery example here...

http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.

http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.

3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.

Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:

<?php

function storeAddress(){

    require_once('MCAPI.class.php');  // same directory as store-address.php

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('123456789-us2');

    $merge_vars = Array( 
        'EMAIL' => $_GET['email'],
        'FNAME' => $_GET['fname'], 
        'LNAME' => $_GET['lname']
    );

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "123456a";

    if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
        // It worked!   
        return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
    }else{
        // An error ocurred, return error message   
        return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>

4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.

Here is something like what my index.html file looks like:

<form id="signup" action="index.html" method="get">
    <input type="hidden" name="ajax" value="true" />
    First Name: <input type="text" name="fname" id="fname" />
    Last Name: <input type="text" name="lname" id="lname" />
    email Address (required): <input type="email" name="email" id="email" />
    HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
    Text: <input type="radio" name="emailtype" value="text" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("<span class='error'>Adding your email address...</span>");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            data: $('#signup').serialize(),
            success: function(msg) {
                $('#message').html(msg);
            }
        });
        return false;
    });
});
</script>

Required pieces...

  • index.html constructed as above or similar. With jQuery, the appearance and options are endless.

  • store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.

  • MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

How to highlight text using javascript

I was wondering that too, you could try what I learned on this post.

I used:

_x000D_
_x000D_
function highlightSelection() {_x000D_
   var userSelection = window.getSelection();_x000D_
   for(var i = 0; i < userSelection.rangeCount; i++) {_x000D_
    highlightRange(userSelection.getRangeAt(i));_x000D_
   }_x000D_
   _x000D_
  }_x000D_
   _x000D_
   function highlightRange(range) {_x000D_
       var newNode = document.createElement("span");_x000D_
       newNode.setAttribute(_x000D_
          "style",_x000D_
          "background-color: yellow; display: inline;"_x000D_
       );_x000D_
       range.surroundContents(newNode);_x000D_
   }
_x000D_
<html>_x000D_
 <body contextmenu="mymenu">_x000D_
_x000D_
  <menu type="context" id="mymenu">_x000D_
   <menuitem label="Highlight Yellow" onclick="highlightSelection()" icon="/images/comment_icon.gif"></menuitem>_x000D_
  </menu>_x000D_
  <p>this is text, select and right click to high light me! if you can`t see the option, please use this<button onclick="highlightSelection()">button </button><p>
_x000D_
_x000D_
_x000D_

you could also try it here: http://henriquedonati.com/projects/Extension/extension.html

xc

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

open read and close a file in 1 line of code

with open('pagehead.section.htm')as f:contents=f.read()

Display alert message and redirect after click on accept

The redirect function cleans the output buffer and does a header('Location:...'); redirection and exits script execution. The part you are trying to echo will never be outputted.

You should either notify on the download page or notify on the page you redirect to about the missing data.

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

rsync copy over only certain types of files using include option

Wrote this handy function and put in my bash scripts or ~/.bash_aliases. Tested sync'ing locally on Linux with bash and awk installed. It works

selrsync(){
# selective rsync to sync only certain filetypes;
# based on: https://stackoverflow.com/a/11111793/588867
# Example: selrsync 'tsv,csv' ./source ./target --dry-run
types="$1"; shift; #accepts comma separated list of types. Must be the first argument.
includes=$(echo $types| awk  -F',' \
    'BEGIN{OFS=" ";}
    {
    for (i = 1; i <= NF; i++ ) { if (length($i) > 0) $i="--include=*."$i; } print
    }')
restargs="$@"

echo Command: rsync -avz --prune-empty-dirs --include="*/" $includes --exclude="*" "$restargs"
eval rsync -avz --prune-empty-dirs --include="*/" "$includes" --exclude="*" $restargs
}

Avantages:

short handy and extensible when one wants to add more arguments (i.e. --dry-run).

Example:

selrsync 'tsv,csv' ./source ./target --dry-run

How to ensure that there is a delay before a service is started in systemd?

Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service like so:

ExecStartPost=/bin/sleep 30

This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).

Android SharedPreferences in Fragment

The marked answer didn't work for me, I had to use

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

EDIT:

Or just try removing the this:

SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

MySQL DELETE FROM with subquery as condition

you can use the alias in this way on the delete statement

DELETE  th.*
FROM term_hierarchy th
INNER JOIN term_hierarchy th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th.parent = 1015;

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

You probably don't have the System.Configuration dll added to the project references. It is not there by default, and you have to add it manually.

Right-click on the References and search for System.Configuration in the .net assemblies.

Check to see if it is in your references...

enter image description here

Right-click and select Add Reference...

enter image description here

Find System.Configuration in the list of .Net Assemblies, select it, and click Ok...

enter image description here

The assembly should now appear in your references...

enter image description here

Find the most popular element in int[] array

Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like @narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:

private static int getMostPopularElement(int[] a){
    int counter = 0, curr, maxvalue, maxcounter = -1;
    maxvalue = curr = a[0];

    for (int e : a){
        if (curr == e){
            counter++;
        } else {
            if (counter > maxcounter){
                maxcounter = counter;
                maxvalue = curr;
            }
            counter = 0;
            curr = e;
        }
    }
    if (counter > maxcounter){
        maxvalue = curr;
    }

    return maxvalue;
}


public static void main(String[] args) {
    System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}

If the array is not sorted, sort it with Arrays.sort(a);

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

How can I remove the last character of a string in python?

To remove the last character, just use a slice: my_file_path[:-1]. If you only want to remove a specific set of characters, use my_file_path.rstrip('/'). If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.

Using curl POST with variables defined in bash script functions

We can assign a variable for curl using single quote ' and wrap some other variables in double-single-double quote "'" for substitution inside curl-variable. Then easily we can use that curl-variable which here is MERGE.

Example:

# other variables ... 
REF_NAME="new-branch";

# variable for curl using single quote => ' not double "
MERGE='{
    "repository": "tmp",
    "command": "git",
    "args": [
        "pull",
        "origin",
        "'"$REF_NAME"'"
    ],
    "options": {
        "cwd": "/home/git/tmp"
    }
}';

notice this line:

    "'"$REF_NAME"'"

and then calling curl as usual:

curl -s -X POST localhost:1365/M -H 'Content-Type: application/json' --data "$MERGE" 

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

Merging two images with PHP

Merger two image png and jpg/png [Image Masking]

//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);

//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

list($src_w, $src_h) = getimagesize($src_url);

//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);

//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);

imagecopymerge_alpha

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
    {
        $cut = imagecreatetruecolor($src_w, $src_h);
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

querySelectorAll with multiple conditions

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

...will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("div.foo");

...will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll("div.foo, p.bar, div legend");

...which means "Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that's also inside a div."

How do I write a Windows batch script to copy the newest file from a directory?

To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END

Printing Lists as Tabular Data

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

python int( ) function

import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

Delete rows with blank values in one particular column

An elegant solution with dplyr would be:

df %>%
  # recode empty strings "" by NAs
  na_if("") %>%
  # remove NAs
  na.omit

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

Remove .php extension with .htaccess

Here is the code that I used to hide the .php extension from the filename:

## hide .php extension
# To redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L,NC]

Note: R=301 is for permanent redirect and is recommended to use for SEO purpose. However if one wants just a temporary redirect replace it with just R

Open Source Javascript PDF viewer

You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.

I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

Bash syntax error: unexpected end of file

This was happening for me when I was trying to call a function using parens, e.g.

run() {
  echo hello
}

run()

should be:

run() {
  echo hello
}

run

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

Converting from longitude\latitude to Cartesian coordinates

Here's the answer I found:

Just to make the definition complete, in the Cartesian coordinate system:

  • the x-axis goes through long,lat (0,0), so longitude 0 meets the equator;
  • the y-axis goes through (0,90);
  • and the z-axis goes through the poles.

The conversion is:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

Where R is the approximate radius of earth (e.g. 6371 km).

If your trigonometric functions expect radians (which they probably do), you will need to convert your longitude and latitude to radians first. You obviously need a decimal representation, not degrees\minutes\seconds (see e.g. here about conversion).

The formula for back conversion:

   lat = asin(z / R)
   lon = atan2(y, x)

asin is of course arc sine. read about atan2 in wikipedia. Don’t forget to convert back from radians to degrees.

This page gives c# code for this (note that it is very different from the formulas), and also some explanation and nice diagram of why this is correct,

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

Activity restart on rotation Android

Every time when screen is rotated, opened activity is finished and onCreate() is called again.

1 . You can do one thing save the state of activity when screen is rotated so that, You can recover all old stuff when activity's onCreate() is called again. Refer this link

2 . If you want to prevent restarting of the activity just place following lines in your manifest.xml file.

  <activity android:name=".Youractivity"
  android:configChanges="orientation|screenSize"/>

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

Optimal way to concatenate/aggregate strings

You can use += to concatenate strings, for example:

declare @test nvarchar(max)
set @test = ''
select @test += name from names

if you select @test, it will give you all names concatenated

Difference between jQuery parent(), parents() and closest() functions

There is difference between both $(this).closest('div') and $(this).parents('div').eq(0)

Basically closest start matching element from the current element whereas parents start matching elements from parent (one level above the current element)

See http://jsfiddle.net/imrankabir/c1jhocre/1/

Speed tradeoff of Java's -Xms and -Xmx options

  1. Allocation always depends on your OS. If you allocate too much memory, you could end up having loaded portions into swap, which indeed is slow.
  2. Whether your program runs slower or faster depends on the references the VM has to handle and to clean. The GC doesn't have to sweep through the allocated memory to find abandoned objects. It knows it's objects and the amount of memory they allocate by reference mapping. So sweeping just depends on the size of your objects. If your program behaves the same in both cases, the only performance impact should be on VM startup, when the VM tries to allocate memory provided by your OS and if you use the swap (which again leads to 1.)

Eclipse does not highlight matching variables

Using Alt + Shift + o It works for me!

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using .index:

In [277]:

df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
   a         b
0  0  0.293422
1  1 -1.631018
2  2  0.065344
3  3 -0.417926
4  4  1.925325
5  5  0.167545
6  6 -0.988941
7  7 -0.277446
8  8  1.426912
9  9 -0.114189
In [278]:

df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

How can I get key's value from dictionary in Swift?

For finding value use below

if let a = companies["AAPL"] {
   // a is the value
}

For traversing through the dictionary

for (key, value) in companies {
    print(key,"---", value)
}

Finally for searching key by value you firstly add the extension

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

Then just call

companies.findKey(val : "Apple Inc")

Add a thousands separator to a total with Javascript or jQuery?

This is how I do it:

// 2056776401.50 = 2,056,776,401.50
function humanizeNumber(n) {
  n = n.toString()
  while (true) {
    var n2 = n.replace(/(\d)(\d{3})($|,|\.)/g, '$1,$2$3')
    if (n == n2) break
    n = n2
  }
  return n
}

Or, in CoffeeScript:

# 2056776401.50 = 2,056,776,401.50
humanizeNumber = (n) ->
  n = n.toString()
  while true
    n2 = n.replace /(\d)(\d{3})($|,|\.)/g, '$1,$2$3'
    if n == n2 then break else n = n2
  n

How to store Node.js deployment settings/configuration files?

npm i config

In config/default.json
{
    "app": {
        "port": 3000
    },
    "db": {
        "port": 27017,
        "name": "dev_db_name"
    }
}

In config/production.json
{
    "app": {
        "port": 4000
    },
    "db": {
        "port": 27000,
        "name": "prod_db_name"
    }
}

In index.js

const config = require('config');

let appPort = config.get('app.port');
console.log(`Application port: ${appPort}`);

let dbPort = config.get('db.port');
console.log(`Database port: ${dbPort}`);

let dbName = config.get('db.name');
console.log(`Database name: ${dbName}`);

console.log('NODE_ENV: ' + config.util.getEnv('NODE_ENV'));

$ node index.js
Application port: 3000
Database port: 27017
Database name: dev_db_name
NODE_ENV: development

For production
$ set NODE_ENV=production
$ node index.js
Application port: 4000
Database port: 27000
Database name: prod_db_name
NODE_ENV: production

Get last record of a table in Postgres

If you accept a tip, create an id in this table like serial. The default of this field will be:

nextval('table_name_field_seq'::regclass).

So, you use a query to call the last register. Using your example:

pg_query($connection, "SELECT currval('table_name_field_seq') AS id;

I hope this tip helps you.

Best way to pretty print a hash

Use the answers above if you're printing to users.

If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)

gem install pry

And check this railscast:

http://railscasts.com/episodes/280-pry-with-rails

Call fragment from fragment

Just do that: getTabAt(index of your tab)

        ActionBar actionBar = getSupportActionBar();
        actionBar.selectTab(actionBar.getTabAt(0));

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

How to Convert date into MM/DD/YY format in C#

See, here you can get only date by passing a format string. You can get a different date format as per your requirement as given below for current date:

DateTime.Now.ToString("M/d/yyyy");

Result : "9/1/2016"

DateTime.Now.ToString("M-d-yyyy");

Result : "9-1-2016"

DateTime.Now.ToString("yyyy-MM-dd");

Result : "2016-09-01"

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

Result : "2016-09-01 09:20:10"

For more details take a look at MSDN reference for Custom Date and Time Format Strings

Cannot kill Python script with Ctrl-C

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

Greyscale Background Css Images

Here you go:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(yourimagehere.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(yourimagehere.jpg);
    }
</style>
</head>
<body>
    <div class="nongrayscale">
        this is a non-grayscale of the bg image
    </div>
    <div class="grayscale">
        this is a grayscale of the bg image
    </div>
</body>
</html>

Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.Grayscale Background Image in DIV Sample

EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
    }
</style>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#image").mouseover(function () {
                $(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
            });
            $("#image").mouseout(function () {
                $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
            });
        });
</script>
</head>
<body>
    <div id="image" class="nongrayscale">
        rollover this image to toggle grayscale
    </div>
</body>
</html>

EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.

_x000D_
_x000D_
<svg>_x000D_
  <defs>_x000D_
    <filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
      <feColorMatrix type="saturate" values="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Making a POST call instead of GET using urllib2

This may have been answered before: Python URLLib / URLLib2 POST.

Your server is likely performing a 302 redirect from http://myserver/post_service to http://myserver/post_service/. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url to http://myserver/post_service/.

Oracle 11g SQL to get unique values in one column of a multi-column query

select person, language     
from table A     
group by person, language  

will return unique rows

Installing NumPy via Anaconda in Windows

I had the same problem, getting the message "ImportError: No module named numpy".

I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:

conda list

So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:

conda install numpy

After I did that, the error with the import numpy was gone

Do HttpClient and HttpClientHandler have to be disposed between requests?

Since it doesn't appear that anyone has mentioned it here yet, the new best way to manage HttpClient and HttpClientHandler in .NET Core 2.1 is using HttpClientFactory.

It solves most of the aforementioned issues and gotchas in a clean and easy-to-use way. From Steve Gordon's great blog post:

Add the following packages to your .Net Core (2.1.1 or later) project:

Microsoft.AspNetCore.All
Microsoft.Extensions.Http

Add this to Startup.cs:

services.AddHttpClient();

Inject and use:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly IHttpClientFactory _httpClientFactory;

    public ValuesController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var client = _httpClientFactory.CreateClient();
        var result = await client.GetStringAsync("http://www.google.com");
        return Ok(result);
    }
}

Explore the series of posts in Steve's blog for lots more features.

Cosine Similarity between 2 Number Lists

import math
from itertools import izip

def dot_product(v1, v2):
    return sum(map(lambda x: x[0] * x[1], izip(v1, v2)))

def cosine_measure(v1, v2):
    prod = dot_product(v1, v2)
    len1 = math.sqrt(dot_product(v1, v1))
    len2 = math.sqrt(dot_product(v2, v2))
    return prod / (len1 * len2)

You can round it after computing:

cosine = format(round(cosine_measure(v1, v2), 3))

If you want it really short, you can use this one-liner:

from math import sqrt
from itertools import izip

def cosine_measure(v1, v2):
    return (lambda (x, y, z): x / sqrt(y * z))(reduce(lambda x, y: (x[0] + y[0] * y[1], x[1] + y[0]**2, x[2] + y[1]**2), izip(v1, v2), (0, 0, 0)))

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

Twitter API - Display all tweets with a certain hashtag?

The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

Open-Source Examples of well-designed Android Applications?

https://github.com/google/iosched

This is the repo for the Google I/O App.

(Current version is 2015, also has tags for 2011 through 2014).

Sources for these books: http://commonsware.com/books

https://github.com/yanchenko/droidparts (a shameless plug)

Difference between HashMap and Map in Java..?

Map is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap is an implementation of that interface.

Why can't I shrink a transaction log file, even after backup?

'sp_removedbreplication' didn't solve the issue for me as SQL just returned saying that the Database wasn't part of a replication...

I found my answer here:

Basically I had to create a replication, reset all of the replication pointers to Zero; then delete the replication I had just made. i.e.

Execute SP_ReplicationDbOption {DBName},Publish,true,1
GO
Execute sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1
GO
DBCC ShrinkFile({LogFileName},0)
GO
Execute SP_ReplicationDbOption {DBName},Publish,false,1
GO

Convert xlsx to csv in Linux with command line

Another option would be to use R via a small bash wrapper for convenience:

xlsx2txt(){
echo '
require(xlsx)
write.table(read.xlsx2(commandArgs(TRUE)[1], 1), stdout(), quote=F, row.names=FALSE, col.names=T, sep="\t")
' | Rscript --vanilla - $1 2>/dev/null
}

xlsx2txt file.xlsx > file.txt

Unable to import a module that is definitely installed

I had similar problem (on Windows) and the root cause in my case was ANTIVIRUS software! It has "Auto-Containment" feature, that wraps running process with some kind of a virtual machine. Symptoms are: pip install somemodule works fine in one cmd-line window and import somemodule fails when executed from another process with the error

ModuleNotFoundError: No module named 'somemodule'

I hope it will save some time to somebody :)

How to compare two date values with jQuery

check the solution provided here it may help, i use it in my projects. http://trentrichardson.com/examples/timepicker/ .(in the end of the page)

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I'm on Android Studio 3.1 Build #AI-173.4670197, built on March 22, 2018 JRE: 1.8.0_152-release-1024-b02 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.

I had the same issue and it only worked after changing my build.grade file to

    compileOptions {                                                          
    sourceCompatibility JavaVersion.VERSION_1_8 
    targetCompatibility JavaVersion.VERSION_1_8


}

Prior to this change nothing worked and all compiles would fail. previously my settings were

sourceCompatibility JavaVersion.VERSION_1_7 
targetCompatibility JavaVersion.VERSION_1_8

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

LINQ query on a DataTable

var results = from myRow in myDataTable
where results.Field<Int32>("RowNo") == 1
select results;

Custom pagination view in Laravel 5

I use this code with k7 theme and use this code with their built in class. You can also use this code with your theme and your class as you need..

try to do this.

<section class="page-paging pt-0">
  <div class="container">
    <div class="row">
      <div class="col-12">
        <nav aria-label="Page navigation example">
          @if ($view_post->lastPage() > 1)
            <ul class="pager list-inline mb-0 text-center">
              <li class="{{ ($view_post->currentPage() == 1) ? ' disabled' : '' }}p-1 list-inline-item float-sm-left">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url(1) }}">
                  <i class="fa fa-angle-left pr-1"></i> Prev
                </a>
              </li>
              @for ($i = 1; $i <= $view_post->lastPage(); $i++)
              <li class=" p-1 list-inline-item d-none d-md-inline-block">
                <a class="{{ ($view_post->currentPage() == $i) ? ' active' : '' }} page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($i) }}">{{ $i }}
                </a>
              </li>
              @endfor
              <li class="{{ ($view_post->currentPage() == $view_post->lastPage()) ? ' disabled' : '' }} p-1 list-inline-item float-sm-right">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($view_post->currentPage()+1) }}"> Next 
                  <i class="fa fa-angle-right pl-1"></i>
                </a>
              </li>
            </ul>
          @endif
        </nav>
      </div>
    </div>
  </div>
</section>

ng-mouseover and leave to toggle item using mouse in angularjs

I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)

<ul ng-repeat="task in tasks">
    <li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
    <span ng-show="hoverEdit"><a>Edit</a></span>
</ul>

How to rotate the background image in the container?

CSS:

.reverse {
  transform: rotate(180deg);
}

.rotate {
  animation-duration: .5s;
  animation-iteration-count: 1;
  animation-name: yoyo;
  animation-timing-function: linear;
}

@keyframes yoyo {
  from { transform: rotate(  0deg); }
  to   { transform: rotate(360deg); }
}

Javascript:

$(buttonElement).click(function () {
  $(".arrow").toggleClass("reverse")

  return false
})

$(buttonElement).hover(function () {
  $(".arrow").addClass("rotate")
}, function() {
  $(".arrow").removeClass("rotate")
})

PS: I've found this somewhere else but don't remember the source

Null check in an enhanced for loop

Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.

for this import org.apache.commons.collections.CollectionUtils.

Maven dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.0</version>
</dependency>

How to save image in database using C#

You'll want to convert the image to a byte[] in C#, and then you'll have the database column as varbinary(MAX)

After that, it's just like saving any other data type.

How to start/stop/restart a thread in Java?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

Changing element style attribute dynamically using JavaScript

I would recommend using a function, which accepts the element id and an object containing the CSS properties, to handle this. This way you write multiple styles at once and use standard CSS property syntax.

//function to handle multiple styles
function setStyle(elId, propertyObject) {
    var el = document.getElementById(elId);
    for (var property in propertyObject) {
        el.style[property] = propertyObject[property];
    }
}

setStyle('xyz', {'padding-top': '10px'});

Better still you could store the styles in a variable, which will make for much easier property management e.g.

var xyzStyles = {'padding-top':'10px'}
setStyle('xyz', xyzStyles);

Hope that helps

Algorithm for solving Sudoku

Using google ortools - the following will either generate a dummy sudoku array or will solve a candidate. The code is probably more verbose than required, any feedback is appreciated.

The idea is to solve a constraint-programming problem that involves

  1. List of 81 variables with integer bounds between 1 and 9.
  2. All different constraint for row vector
  3. All different constraint for column vector
  4. All different constraint for the sub-matrices

In addition, when trying to solve existing sudoku, we add additional constraints on variables that already have assigned value.

from ortools.constraint_solver import pywrapcp
import numpy as np

def sudoku_solver(candidate = None):
    solver = pywrapcp.Solver("Sudoku")

    variables = [solver.IntVar(1,9,f"x{i}") for i in range(81)]
    if len(candidate)>0:
        candidate = np.int64(candidate)
        for i in range(81):
            val = candidate[i]
            if val !=0:
                solver.Add(variables[i] == int(val))

    def set_constraints():
        for i in range(9):
            # All columns should be different
            q=[variables[j] for j in list(range(i,81,9))]
            solver.Add(solver.AllDifferent(q))

            #All rows should be different
            q2=[variables[j] for j in list(range(i*9,(i+1)*9))]
            solver.Add(solver.AllDifferent(q2))

            #All values in the sub-matrix should be different
            a = list(range(81))
            sub_blocks = a[3*i:3*(i+9):9] + a[3*i+1:3*(i+9)+1:9] + a[3*i+2:3*(i+9)+2:9]
            q3 = [variables[j] for j in sub_blocks]
            solver.Add(solver.AllDifferent(q3))
            
    set_constraints()
    db = solver.Phase(variables, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE)
    solver.NewSearch(db)    
    
    results_store =[]
    num_solutions =0
    total_solutions = 5
    while solver.NextSolution() and num_solutions<total_solutions:
        results = [j.Value() for j in variables]
        results_store.append(results)
        num_solutions +=1
        
    return results_store

Solve the following sudoku

candidate = np.array([0, 2, 0, 4, 5, 6, 0, 8, 0, 0, 5, 6, 7, 8, 9, 0, 0, 3, 7, 0, 9, 0,
       2, 0, 4, 5, 6, 2, 0, 1, 5, 0, 4, 8, 9, 7, 5, 0, 4, 8, 0, 0, 0, 0,
       0, 3, 1, 0, 6, 4, 5, 9, 7, 0, 0, 0, 5, 0, 7, 8, 3, 1, 2, 8, 0, 7,
       0, 1, 0, 5, 0, 4, 9, 7, 8, 0, 3, 0, 0, 0, 5])


results_store = sudoku_solver(candidate)  

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

How to check if a column exists before adding it to an existing table in PL/SQL?

Or, you can ignore the error:

declare
    column_exists exception;
    pragma exception_init (column_exists , -01430);
begin
    execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
    exception when column_exists then null;
end;
/

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

Could not open input file: artisan

Try executing it as sudo.

sudo laravel new blog

Your file may not have the appropriate permissions. Let us know if it worked!

Mockito How to mock only the call of a method of the superclass

Even if i totally agree with iwein response (

favor composition over inheritance

), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.

So, my suggestion :

/**
 * BaseService is now an asbtract class encapsulating 
 * some common logic callable by child implementations
 */
abstract class BaseService {  
    protected void commonSave() {
        // Put your common work here
    }

    abstract void save();
}

public ChildService extends BaseService {  
    public void save() {
        // Put your child specific work here
        // ...

        this.commonSave();
    }  
}

And then, in the unit test :

    ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);

    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Boolean answer(InvocationOnMock invocation)
                throws Throwable {
            // Put your mocked behavior of BaseService.commonSave() here
            return null;
        }
    }).when(childSrv).commonSave();

    childSrv.save();

    Mockito.verify(childSrv, Mockito.times(1)).commonSave();

    // Put any other assertions to check child specific work is done

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

How to remove old and unused Docker images

I'm using this command:

export BEFORE_DATETIME=$(date --date='10 weeks ago' +"%Y-%m-%dT%H:%M:%S.%NZ")
docker images -q | while read IMAGE_ID; do
    export IMAGE_CTIME=$(docker inspect --format='{{.Created}}' --type=image ${IMAGE_ID})
    if [[ "${BEFORE_DATETIME}" > "${IMAGE_CTIME}" ]]; then
        echo "Removing ${IMAGE_ID}, ${BEFORE_DATETIME} is earlier then ${IMAGE_CTIME}"
        docker rmi -f ${IMAGE_ID};
    fi;
done

This will remove all images whose creation time is greater than 10 weeks ago.

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

ReactJS Two components communicating

I once was where you are right now, as a beginner you sometimes feel out of place on how the react way to do this. I'm gonna try to tackle the same way I think of it right now.

States are the cornerstone for communication

Usually what it comes down to is the way that you alter the states in this component in your case you point out three components.

<List /> : Which probably will display a list of items depending on a filter <Filters />: Filter options that will alter your data. <TopBar />: List of options.

To orchestrate all of this interaction you are going to need a higher component let's call it App, that will pass down actions and data to each one of this components so for instance can look like this

<div>
  <List items={this.state.filteredItems}/>
  <Filter filter={this.state.filter} setFilter={setFilter}/>
</div>

So when setFilter is called it will affect the filteredItem and re-render both component;. In case this is not entirely clear I made you an example with checkbox that you can check in a single file:

import React, {Component} from 'react';
import {render} from 'react-dom';

const Person  = ({person, setForDelete}) => (
          <div>
            <input type="checkbox" name="person" checked={person.checked} onChange={setForDelete.bind(this, person)} />
            {person.name}
          </div>
);


class PeopleList extends Component {

  render() {

    return(
      <div>
       {this.props.people.map((person, i) => {
         return <Person key={i} person={person} setForDelete={this.props.setForDelete} />;
       })}
       <div onClick={this.props.deleteRecords}>Delete Selected Records</div>
     </div>
    );
  }

} // end class

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {people:[{id:1, name:'Cesar', checked:false},{id:2, name:'Jose', checked:false},{id:3, name:'Marbel', checked:false}]}
  }

  deleteRecords() {
    const people = this.state.people.filter(p => !p.checked);

    this.setState({people});
 }

  setForDelete(person) {
    const checked = !person.checked;
    const people = this.state.people.map((p)=>{
      if(p.id === person.id)
        return {name:person.name, checked};
      return p;
    });

    this.setState({people});
  }

  render () {

    return <PeopleList people={this.state.people} deleteRecords={this.deleteRecords.bind(this)} setForDelete={this.setForDelete.bind(this)}/>;
  }
}

render(<App/>, document.getElementById('app'));

Hidden features of Windows batch files

Quick edit mode in cmd.exe is my favorite. This is slightly off topic, but when interacting with the command shell it can be a lifesaver. No, I'm not being hyperbolic--you will only see caret-capitol-v a certain number of times before you die; the more you see, the faster you die.

  1. Open up regedit (caution, not my fault, blue screen, etc)
  2. Go to HKCU/Console
  3. Set QuickEdit to 1

(You can set this from the UI as well, which is probably the better way. See the comments for instructions. Also there's a nice one line script to do this as well.)

Now, to copy, just left-click and drag to select and right click to copy. To paste, just right click.

NO MORE ^V^V^V^V^V^V^V^V^V^V^V^V^V^V!!!

Crap, I think I just killed somebody. Sorry!

Two statements next to curly brace in an equation

You can try the cases env in amsmath.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  f(x)=\begin{cases}
    1, & \text{if $x<0$}.\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}

\end{document}

amsmath cases

center MessageBox in parent form

I really needed this in C# and found Center MessageBox C#

Here's a nicely formatted version

using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;   

public class MessageBoxEx
{
    private static IWin32Window _owner;
    private static HookProc _hookProc;
    private static IntPtr _hHook;

    public static DialogResult Show(string text)
    {
        Initialize();
        return MessageBox.Show(text);
    }

    public static DialogResult Show(string text, string caption)
    {
        Initialize();
        return MessageBox.Show(text, caption);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon, defButton);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon, defButton, options);
    }

    public static DialogResult Show(IWin32Window owner, string text)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon,
                               defButton, options);
    }

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

    public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);

    public const int WH_CALLWNDPROCRET = 12;

    public enum CbtHookAction : int
    {
        HCBT_MOVESIZE = 0,
        HCBT_MINMAX = 1,
        HCBT_QS = 2,
        HCBT_CREATEWND = 3,
        HCBT_DESTROYWND = 4,
        HCBT_ACTIVATE = 5,
        HCBT_CLICKSKIPPED = 6,
        HCBT_KEYSKIPPED = 7,
        HCBT_SYSCOMMAND = 8,
        HCBT_SETFOCUS = 9
    }

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("User32.dll")]
    public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

    [DllImport("User32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll")]
    public static extern int UnhookWindowsHookEx(IntPtr idHook);

    [DllImport("user32.dll")]
    public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

    [DllImport("user32.dll")]
    public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

    [StructLayout(LayoutKind.Sequential)]
    public struct CWPRETSTRUCT
    {
        public IntPtr lResult;
        public IntPtr lParam;
        public IntPtr wParam;
        public uint message;
        public IntPtr hwnd;
    } ;

    static MessageBoxEx()
    {
        _hookProc = new HookProc(MessageBoxHookProc);
        _hHook = IntPtr.Zero;
    }

    private static void Initialize()
    {
        if (_hHook != IntPtr.Zero)
        {
            throw new NotSupportedException("multiple calls are not supported");
        }

        if (_owner != null)
        {
            _hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
        }
    }

    private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0)
        {
            return CallNextHookEx(_hHook, nCode, wParam, lParam);
        }

        CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
        IntPtr hook = _hHook;

        if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
        {
            try
            {
                CenterWindow(msg.hwnd);
            }
            finally
            {
                UnhookWindowsHookEx(_hHook);
                _hHook = IntPtr.Zero;
            }
        }

        return CallNextHookEx(hook, nCode, wParam, lParam);
    }

    private static void CenterWindow(IntPtr hChildWnd)
    {
        Rectangle recChild = new Rectangle(0, 0, 0, 0);
        bool success = GetWindowRect(hChildWnd, ref recChild);

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        Rectangle recParent = new Rectangle(0, 0, 0, 0);
        success = GetWindowRect(_owner.Handle, ref recParent);

        Point ptCenter = new Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        Point ptStart = new Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
        ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;

        int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
                                height, false);
    }

}

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

Thanks to Erhun's answer I finally realised that my JSON mapper was returning the quotation marks around my data too! I needed to use "asText()" instead of "toString()"

It's not an uncommon issue - one's brain doesn't see anything wrong with the correct data, surrounded by quotes!

discoveryJson.path("some_endpoint").toString();
"https://what.the.com/heck"

discoveryJson.path("some_endpoint").asText();
https://what.the.com/heck

Bulk Insert to Oracle using .NET

Oracle says (http://www.oracle.com/technology/products/database/utilities/htdocs/sql_loader_overview.html)

SQL*Loader is the primary method for quickly populating Oracle tables with data from external files

My experience is that their loader loads their tables faster than anything else.

Recommended way to get hostname in Java

As others have noted, getting the hostname based on DNS resolution is unreliable.

Since this question is unfortunately still relevant in 2018, I'd like to share with you my network-independent solution, with some test runs on different systems.

The following code tries to do the following:

  • On Windows

    1. Read the COMPUTERNAME environment variable through System.getenv().

    2. Execute hostname.exe and read the response

  • On Linux

    1. Read the HOSTNAME environment variable through System.getenv()

    2. Execute hostname and read the response

    3. Read /etc/hostname (to do this I'm executing cat since the snippet already contains code to execute and read. Simply reading the file would be better, though).

The code:

public static void main(String[] args) throws IOException {
    String os = System.getProperty("os.name").toLowerCase();

    if (os.contains("win")) {
        System.out.println("Windows computer name through env:\"" + System.getenv("COMPUTERNAME") + "\"");
        System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
    } else if (os.contains("nix") || os.contains("nux") || os.contains("mac os x")) {
        System.out.println("Unix-like computer name through env:\"" + System.getenv("HOSTNAME") + "\"");
        System.out.println("Unix-like computer name through exec:\"" + execReadToString("hostname") + "\"");
        System.out.println("Unix-like computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
    }
}

public static String execReadToString(String execCommand) throws IOException {
    try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
        return s.hasNext() ? s.next() : "";
    }
}

Results for different operating systems:

macOS 10.13.2

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

OpenSuse 13.1

Unix-like computer name through env:"machinename"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

Ubuntu 14.04 LTS This one is kinda strange since echo $HOSTNAME returns the correct hostname, but System.getenv("HOSTNAME") does not:

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:"machinename
"

EDIT: According to legolas108, System.getenv("HOSTNAME") works on Ubuntu 14.04 if you run export HOSTNAME before executing the Java code.

Windows 7

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

Windows 10

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

The machine names have been replaced but I kept the capitalization and structure. Note the extra newline when executing hostname, you might have to take it into account in some cases.

How to check empty object in angular 2 template using *ngIf

A bit of a lengthier way (if interested in it):

In your typescript code do this:

this.objectLength = Object.keys(this.previous_info).length != 0;

And in the template:

ngIf="objectLength != 0"

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Add comma to numbers every three digits

You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Mongoose query where value is not null

Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:

    const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';

  // Get the _ids of users with the role equal to role.
    await User.find({role: role}, {_id: 1, role: 1, name: 1},  function(err, docs) {

        // Map the docs into an array of just the _ids
        var ids = docs.map(function(doc) { return doc._id; });

        // Get the profiles whose users are in that set.
        Profile.find({user: {$in: ids}}, function(err, profiles) {
            // docs contains your answer
            res.json({
                code: 200,
                profiles: profiles,
                page: page
            })
        })
        .select(exclude)
        .populate({
            path: 'user',
            select: '-password -verified -_id -__v'
            // group: { role: "$role"} 
          })
    });

What is the most efficient way to deep clone an object in JavaScript?

Requires new-ish browsers, but...

Let's extend the native Object and get a real .extend();

Object.defineProperty(Object.prototype, 'extend', {
    enumerable: false,
    value: function(){
        var that = this;

        Array.prototype.slice.call(arguments).map(function(source){
            var props = Object.getOwnPropertyNames(source),
                i = 0, l = props.length,
                prop;

            for(; i < l; ++i){
                prop = props[i];

                if(that.hasOwnProperty(prop) && typeof(that[prop]) === 'object'){
                    that[prop] = that[prop].extend(source[prop]);
                }else{
                    Object.defineProperty(that, prop, Object.getOwnPropertyDescriptor(source, prop));
                }
            }
        });

        return this;
    }
});

Just pop that in prior to any code that uses .extend() on an object.

Example:

var obj1 = {
    node1: '1',
    node2: '2',
    node3: 3
};

var obj2 = {
    node1: '4',
    node2: 5,
    node3: '6'
};

var obj3 = ({}).extend(obj1, obj2);

console.log(obj3);
// Object {node1: "4", node2: 5, node3: "6"}

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

json_encode(): Invalid UTF-8 sequence in argument

I am very late but if some one working on SLIM to make rest api and getting same error can solve this problem by adding below line as:

<?php

// DbConnect.php file
class DbConnect
{
    //Variable to store database link
    private $con;

    //Class constructor
    function __construct()
    {

    }

    //This method will connect to the database
    function connect()
    {
        //Including the constants.php file to get the database constants
        include_once dirname(__FILE__) . '/Constants.php';

        //connecting to mysql database
        $this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        mysqli_set_charset($this->con, "utf8"); // add this line 
        //Checking if any error occured while connecting
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        //finally returning the connection link
        return $this->con;
    }
}

Detecting superfluous #includes in C/C++?

Google's cppclean (links to: download, documentation) can find several categories of C++ problems, and it can now find superfluous #includes.

There's also a Clang-based tool, include-what-you-use, that can do this. include-what-you-use can even suggest forward declarations (so you don't have to #include so much) and optionally clean up your #includes for you.

Current versions of Eclipse CDT also have this functionality built in: going under the Source menu and clicking Organize Includes will alphabetize your #include's, add any headers that Eclipse thinks you're using without directly including them, and comments out any headers that it doesn't think you need. This feature isn't 100% reliable, however.

How to include view/partial specific styling in AngularJS

@tennisgent's solution is great. However, I think is a little limited.

Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

For a full solution I suggest using AngularCSS.

  1. Supports Angular's ngRoute, UI Router, directives, controllers and services.
  2. Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  3. You can customize where the stylesheets are injected: head, body, custom selector, etc...
  4. Supports preloading, persisting and cache busting
  5. Supports media queries and optimizes page load via matchMedia API

https://github.com/door3/angular-css

Here are some examples:

Routes

  $routeProvider
    .when('/page1', {
      templateUrl: 'page1/page1.html',
      controller: 'page1Ctrl',
      /* Now you can bind css to routes */
      css: 'page1/page1.css'
    })
    .when('/page2', {
      templateUrl: 'page2/page2.html',
      controller: 'page2Ctrl',
      /* You can also enable features like bust cache, persist and preload */
      css: {
        href: 'page2/page2.css',
        bustCache: true
      }
    })
    .when('/page3', {
      templateUrl: 'page3/page3.html',
      controller: 'page3Ctrl',
      /* This is how you can include multiple stylesheets */
      css: ['page3/page3.css','page3/page3-2.css']
    })
    .when('/page4', {
      templateUrl: 'page4/page4.html',
      controller: 'page4Ctrl',
      css: [
        {
          href: 'page4/page4.css',
          persist: true
        }, {
          href: 'page4/page4.mobile.css',
          /* Media Query support via window.matchMedia API
           * This will only add the stylesheet if the breakpoint matches */
          media: 'screen and (max-width : 768px)'
        }, {
          href: 'page4/page4.print.css',
          media: 'print'
        }
      ]
    });

Directives

myApp.directive('myDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'my-directive/my-directive.html',
    css: 'my-directive/my-directive.css'
  }
});

Additionally, you can use the $css service for edge cases:

myApp.controller('pageCtrl', function ($scope, $css) {

  // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
  $css.bind({ 
    href: 'my-page/my-page.css'
  }, $scope);

  // Simply add stylesheet(s)
  $css.add('my-page/my-page.css');

  // Simply remove stylesheet(s)
  $css.remove(['my-page/my-page.css','my-page/my-page2.css']);

  // Remove all stylesheets
  $css.removeAll();

});

You can read more about AngularCSS here:

http://door3.com/insights/introducing-angularcss-css-demand-angularjs

How to select a dropdown value in Selenium WebDriver using Java

First Import the package as :

import org.openqa.selenium.support.ui.Select;

then write in single line as:

new Select (driver.findElement(By.id("sampleid"))).selectByValue("SampleValue");

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How to install cron

On CentOS/RHEL:

yum install cronie

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Look at ?par for the various graphics parameters.

In general cex controls size, col controls colour. If you want to control the colour of a label, the par is col.lab, the colour of the axis annotations col.axis, the colour of the main text, col.main etc. The names are quite intuitive, once you know where to begin.

For example

x <- 1:10
y <- 1:10

plot(x , y,xlab="x axis", ylab="y axis",  pch=19, col.axis = 'blue', col.lab = 'red', cex.axis = 1.5, cex.lab = 2)

enter image description here

If you need to change the colour / style of the surrounding box and axis lines, then look at ?axis or ?box, and you will find that you will be using the same parameter names within calls to box and axis.

You have a lot of control to make things however you wish.

eg

plot(x , y,xlab="x axis", ylab="y axis",  pch=19,  cex.lab = 2, axes = F,col.lab = 'red')
box(col = 'lightblue')
axis(1, col = 'blue', col.axis = 'purple', col.ticks = 'darkred', cex.axis = 1.5, font = 2, family = 'serif')
axis(2, col = 'maroon', col.axis = 'pink', col.ticks = 'limegreen', cex.axis = 0.9, font =3, family = 'mono')

enter image description here

Which is seriously ugly, but shows part of what you can control

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

Not 100% automatic, but I save a lot of time using Photoshop Actions.

For instance, given xhdpi assets, I then create a task for hdpi and mdpi, that scales to 66.66% and to 44.44% respectively. Then I run the actions for all images on folder xhdpi.

For 512x512 images, all you have to do is calculate which percentage should you scale your images to achieve xxhpi, xhdpi, hdpi, and mdpi.

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

currently unable to handle this request HTTP ERROR 500

I was having "(...) unable to handle this request. http error 500" and found out it was from a require_once that was working locally, on a windows machine, with backslash (\) as separator for directories but when i uploaded to my server it stopped working. I changed it to forward slash (/) and now is ok.

require_once ( 'cards\cards.php' ); // **http error 500**

require_once ( 'cards/cards.php' ); // OK

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

How can I add an ampersand for a value in a ASP.net/C# app config file value

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>

clearing a char array c

Pls find below where I have explained with data in the array after case 1 & case 2.

char sc_ArrData[ 100 ];
strcpy(sc_ArrData,"Hai" );

Case 1:

sc_ArrData[0] = '\0';

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 97 'a'
[2] 105 'i'
[3] 0 ''

Case 2:

memset(&sc_ArrData[0], 0, sizeof(sc_ArrData));

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 0 ''
[2] 0 ''
[3] 0 ''

Though setting first argument to NULL will do the trick, using memset is advisable

How to set aliases in the Git Bash for Windows?

I had the same problem, I can't figured out how to find the aliases used by Git Bash on Windows. After searching for a while, I found the aliases.sh file under C:\Program Files\Git\etc\profile.d\aliases.sh.

This is the path under windows 7, maybe can be different in other installation.

Just open it with your preferred editor in admin mode. After save it, reload your command prompt.

I hope this can help!

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

How do I allow HTTPS for Apache on localhost?

I'd like to add something to the very good answer of @CodeWarrior, that works perfectly on Chrome, but for Firefox needs an additional step.

Since Firefox does not thrust CA Certificates that Windows does by default, you need to go on about:config, scroll down to security.enterprise_roots.enabled and change it to true.

Now your certificate should be seen as valid also on Firefox.

Of course this is only for development purposes, since ssl trust is a critical security concern and change this settings only if you know the implications.

How to keep a Python script output window open?

Start the script from already open cmd window or at the end of script add something like this, in Python 2:

 raw_input("Press enter to exit ;)")

Or, in Python 3:

input("Press enter to exit ;)")

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd-mmm-yy format.

select 
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+  
Right(Year(getdate()),2)

Slick.js: Get current and total slides (ie. 3/5)

Based on the first proposition posted by @Mx. (posted sept.15th 2014) I created a variant to get a decent HTML markup for ARIA support.

$('.slideshow').slick({
    slide: 'img',
    autoplay: true,
    dots: true,
    dotsClass: 'custom_paging',
    customPaging: function (slider, i) {
        //FYI just have a look at the object to find available information
        //press f12 to access the console in most browsers
        //you could also debug or look in the source
        console.log(slider);
        var slideNumber   = (i + 1),
            totalSlides = slider.slideCount;
        return '<a class="custom-dot" role="button" title="' + slideNumber + ' of ' + totalSlides + '"><span class="string">' + slideNumber + '</span></a>';
    }
});

jsFiddle DEMO

Getting the thread ID from a thread

System.Threading.Thread.CurrentThread.Name

System.Threading.Thread.CurrentThread.ManagedThreadId

What is the best way to check for Internet connectivity using .NET?

I am having issue on those method on my 3g Router/modem, because if internet is disconnected the router redirects the page to its response page, so you still get a steam and your code think there is internet. Apples (or others) have a hot-spot-dedection page which always returns a certain response. The following sample returns "Success" response. So you will be exactly sure you could connect the internet and get real response !

public static bool CheckForInternetConnection()
{
    try
    {       
        using (var webClient = new WebClient())
        using (var stream = webClient.OpenRead("http://captive.apple.com/hotspot-detect.html"))
        {
            if (stream != null)
            {
                //return true;
                stream.ReadTimeout = 1000;
                using (var reader = new StreamReader(stream, Encoding.UTF8, false))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line == "<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>")
                        {
                            return true;
                        }
                        Console.WriteLine(line);
                    }
                }

            }
            return false;
        }
    }
    catch
    {

    }
    return false;
}

how to set cursor style to pointer for links without hrefs

Use CSS cursor: pointer if I remember correctly.

Either in your CSS file:

.link_cursor
{
    cursor: pointer;
}

Then just add the following HTML to any elements you want to have the link cursor: class="link_cursor" (the preferred method.)

Or use inline CSS:

<a style="cursor: pointer;">

First letter capitalization for EditText

If you want capital first letter in every word then use android:inputType="textCapWords"

For Better understanding

 <EditText
    android:id="@+id/edt_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textCapWords"/>

And if you capital word for every sentence then use it . android:inputType="textCapSentences" this line in your xml. I mean in your EditText.

For Better understanding

<EditText
    android:id="@+id/edt_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textCapSentences"/>
    

git reset --hard HEAD leaves untracked files behind

You can use git stash. You have to specify --include-untracked, otherwise you'll end up with the original problem.

git stash --include-untracked

Then just drop the last entry in the stash

git stash drop

You can make a handy-dandy alias for that, and call it git discard for example:

git config --global alias.discard "! git stash -q --include-untracked && git stash drop -q"

sql query with multiple where statements

Can we see the structure of your table? If I am understanding this, then the assumption made by the query is that a record can be only meta_key - 'lat' or meta_key = 'long' not both because each row only has one meta_key column and can only contain 1 corresponding value, not 2. That would explain why you don't get results when you connect the with an AND; it's impossible.

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>