Programs & Examples On #Regioninfo

How to hide Table Row Overflow?

In general, if you are using white-space: nowrap; it is probably because you know which columns are going to contain content which wraps (or stretches the cell). For those columns, I generally wrap the cell's contents in a span with a specific class attribute and apply a specific width.

Example:

HTML:

<td><span class="description">My really long description</span></td>

CSS:

span.description {
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    width: 150px;
}

java: HashMap<String, int> not working

You cannot use primitive types in HashMap. int, or double don't work. You have to use its enclosing type. for an example

Map<String,Integer> m = new HashMap<String,Integer>();

Now both are objects, so this will work.

'Access denied for user 'root'@'localhost' (using password: NO)'

Simply edit my.ini file in C:\xampp\mysql\bin path. Just add:

skip-grant-tables

line in between lines of # The MySQL server [mysqld] and port=3306. Then restart the MySQL server.

Looks like:

Screenshot

Slide right to left?

I ran into a similar problem while trying to code a menu for small screen sizes. The solution I went with was to just shov it off the viewport.

I made this using SASS and JQuery (No JQuery UI), but this could all be achieved in native JS and CSS.

https://codepen.io/maxbethke/pen/oNzMLRa

_x000D_
_x000D_
var menuOpen = false

var init = () => {
    $(".menu__toggle, .menu__blackout").on("click", menuToggle)
}

var menuToggle = () => {
    console.log("Menu:Toggle");
    $(".menu__blackout").fadeToggle();

    if(menuOpen) { // close menu
        $(".menu__collapse").css({
            left: "-80vw",
            right: "100vw"
        });
    } else { // open menu
        $(".menu__collapse").css({
            left: "0",
            right: "20vw"
        });
    }

    menuOpen = !menuOpen;
}

$(document).ready(init);
_x000D_
.menu__toggle {
    position: absolute;
    right: 0;
    z-index: 1;
}

.menu__blackout {
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.menu__collapse {
  position: absolute;
  top: 0;
  right: 100vw;
  bottom: 0;
  left: -80vw;
  background: white;
  -webkit-transition: ease-in-out all 1s;
  transition: ease-in-out all 1s;
  z-index: 11;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu__toggle">Toggle menu</button>

<menu class="menu">
  <div class="menu__blackout"></div>
  <div class="menu__collapse">
    <ul class="list">
      <li class="list__item">
        <a class="list__item__link" href="#section1">Menu Item 1</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section2">Menu Item 2</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section3">Menu Item 3</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section4">Menu Item 4</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section5">Menu Item 5</a>
      </li>
    </ul>
  </div>
</menu>
_x000D_
_x000D_
_x000D_

What is the difference between compileSdkVersion and targetSdkVersion?

compiledSdkVersion==> which version of SDK should compile your code to bytecode(it uses in development environment) point: it's better use last version of SDK.

minSdkVersion==> these item uses for installation of APK(it uses in production environment). For example:

if(client-sdk-version   <   min-sdk-versoin )
    client-can-not-install-apk;
else
    client-can-install-apk;

String is immutable. What exactly is the meaning?

see here

class ImmutableStrings {

    public static void main(String[] args) {
        testmethod();
    }

    private static void testmethod() {
    String a="a";
    System.out.println("a 1-->"+a);
    System.out.println("a 1 address-->"+a.hashCode());

    a = "ty";
    System.out.println("a 2-->"+a);

       System.out.println("a 2 address-->"+a.hashCode());
    }
}

output:

a 1-->a
a 1 address-->97
a 2-->ty
a 2 address-->3717

This indicates that whenever you are modifying the content of immutable string object a a new object will be created. i.e you are not allowed to change the content of immutable object. that's why the address are different for both the object.

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

How to check the input is an integer or not in Java?

If the user input is a String then you can try to parse it as an integer using parseInt method, which throws NumberFormatException when the input is not a valid number string:

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");
}

What does ENABLE_BITCODE do in xcode 7?

Update

Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.

Original

More specifically:

Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.

Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.

The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

"Could not find a part of the path" error message

I resolved a similar issue by simply restarting Visual Studio with admin rights.

The problem was because it couldn't open one project related to Sharepoint without elevated access.

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Does Notepad++ show all hidden characters?

For non-printing characters, you can do the following:

  • if you could identify the character, where cursor takes 2 arrow keys to move, just select that character.
  • do Ctrl-F
  • now you can count or replace or even mark all such characters

Suppress Scientific Notation in Numpy When Creating Array From Nested List

You could write a function that converts a scientific notation to regular, something like

def sc2std(x):
    s = str(x)
    if 'e' in s:
        num,ex = s.split('e')
        if '-' in num:
            negprefix = '-'
        else:
            negprefix = ''
        num = num.replace('-','')
        if '.' in num:
            dotlocation = num.index('.')
        else:
            dotlocation = len(num)
        newdotlocation = dotlocation + int(ex)
        num = num.replace('.','')
        if (newdotlocation < 1):
            return negprefix+'0.'+'0'*(-newdotlocation)+num
        if (newdotlocation > len(num)):
            return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
        return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
    else:
        return s

Convert dd-mm-yyyy string to date

Split on "-"

Parse the string into the parts you need:

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

Use regex

var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))

Why not use regex?

Because you know you'll be working on a string made up of three parts, separated by hyphens.

However, if you were looking for that same string within another string, regex would be the way to go.

Reuse

Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:

function toDate(dateStr) {
  var parts = dateStr.split("-")
  return new Date(parts[2], parts[1] - 1, parts[0])
}

Using as:

var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)

Or if you don't mind jQuery in your function:

function toDate(selector) {
  var from = $(selector).val().split("-")
  return new Date(from[2], from[1] - 1, from[0])
}

Using as:

var f = toDate("#datepicker")
var t = toDate("#datepickertwo")

Modern JavaScript

If you're able to use more modern JS, array destructuring is a nice touch also:

const toDate = (dateStr) => {
  const [day, month, year] = dateStr.split("-")
  return new Date(year, month - 1, day)
}

Run a JAR file from the command line and specify classpath

Run a jar file and specify a class path like this:

java -cp <jar_name.jar:libs/*> com.test.App

jar_name.jar is the full name of the JAR you want to execute

libs/* is a path to your dependency JARs

com.test.App is the fully qualified name of the class from the JAR that has the main(String[]) method

The jar and dependent jar should have execute permissions.

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, so now we can simply write

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">

If you are using an earlier version of Angular, your two choices are:

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

E.g.,

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values.

An example of 1) was given above. Here is an example of 3, which I think reads much better:

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

Calculating a 2D Vector's Cross Product

Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:

| a x b | = |a| . |b| . sine(theta)

or

sine(theta) = | a x b | / (|a| . |b|)

So, in implementation 1 above, if a and b are known in advance to be unit vectors then the result of that function is exactly that sine() value.

Overriding fields or properties in subclasses

Option 2 is a non-starter - you can't override fields, you can only hide them.

Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class which is set from a constructor parameter:

abstract class Mother
{
    private readonly int myInt;
    public int MyInt { get { return myInt; } }

    protected Mother(int myInt)
    {
        this.myInt = myInt;
    }
}

class Daughter : Mother
{
    public Daughter() : base(1)
    {
    }
}

That's probably the most appropriate approach if the value doesn't change over the lifetime of the instance.

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

How to run vi on docker container?

USE THIS:

apt-get update && apt-get install -y vim

Explanation of the above command

  1. apt-get update => Will update the current package
  2. apt-get install => Will install the package
  3. -y => Will by pass the permission, default permission will set to Yes.
  4. vim => Name of the package you want to install.

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Connecting to shared virtual machines

Connection to VMware Workstation Server (the shared virtual machines) is administered by the VMware Host Agent service. The service uses TCP ports 80 and 443. This service is also used by other VMware products, including VMware Server and vSphere, and provides additional capabilities. Configuring shared virtual machines

With the Shared VMs Workstation preferences, you can disable/enable the server, assign a different port for connecting, and change the Shared VMs directory.

To access the Shared VMs Workstation preferences:

Go to Edit > Preferences.
Click the Shared VMs tab.

Auto-increment primary key in SQL tables

I think there is a way to do it at definition stage like this

create table employee( id int identity, name varchar(50), primary key(id) ).. I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

How to auto import the necessary classes in Android Studio with shortcut?

On Windows with Android Studio 1.5.1 : File --> Settings --> Editor --> General --> Auto Import

enter image description here

How to properly upgrade node using nvm

Bash alias for updating current active version:

alias nodeupdate='nvm install $(nvm current | sed -rn "s/v([[:digit:]]+).*/\1/p") --reinstall-packages-from=$(nvm current)'

The part sed -rn "s/v([[:digit:]]+).*/\1/p" transforms output from nvm current so that only a major version of node is returned, i.e.: v13.5.0 -> 13.

Minimum Hardware requirements for Android development

Its of no use even if you increase your RAM size because I tried it too. I am using P4 3.00GHz processor and 3 GB RAM(changed from 1 GB to 3GB), But even the Hello world application never turned up.

Its preferable to upgrade your system.

How to detect window.print() finish

Implementing window.onbeforeprint and window.onafterprint

The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70

To approach this I'm using Adam's answer with a simple modification:

     function print() {
    (function () {
       let afterPrintCounter = !!window.chrome ? 0 : 1;
       let beforePrintCounter = !!window.chrome ? 0 : 1;
       var beforePrint = function () {
          beforePrintCounter++;
          if (beforePrintCounter === 2) {
             console.log('Functionality to run before printing.');
          }
       };
       var afterPrint = function () {
          afterPrintCounter++;
          if (afterPrintCounter === 2) {
             console.log('Functionality to run after printing.');
             //window.close();
          }
       };
       if (window.matchMedia) {
          var mediaQueryList = window.matchMedia('print');
          mediaQueryList.addListener(function (mql) {
             if (mql.matches) {
                beforePrint();
             } else {
                afterPrint();
             }
          });
       }
       window.onbeforeprint = beforePrint;
       window.onafterprint = afterPrint;
    }());
    //window.print(); //To print the page when it is loaded
 }

I'm calling it in here:

<body onload="print();">

This works for me. Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla). For detecting the browser you can refer to this answer

Re-render React component when prop changes

I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.

This section of your code:

componentDidMount() {
      if (this.props.isManager) {
        this.props.dispatch(actions.fetchAllSites())
      } else {
        const currentUserId = this.props.user.get('id')
        this.props.dispatch(actions.fetchUsersSites(currentUserId))
      }  
    }

Should not be triggering in a component, it should be handled after executing your first request.

Have a look at this example from redux-thunk:

function makeASandwichWithSecretSauce(forPerson) {

  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.

Getting command-line password input in Python

15.7. getpass — Portable password input

#!/usr/bin/python3
from getpass import getpass
passwd = getpass("password: ")
print(passwd)

You can read more here

How to spyOn a value property (rather than a method) with Jasmine

Any reason you cannot just change it on the object directly? It is not as if javascript enforces visibility of a property on an object.

How to print the values of slices

I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.

package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}

This code is going produce and output like this one:

enter image description here


For more details, please read: https://github.com/inancgumus/prettyslice

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

Hex transparency in colors

Using python to calculate this, for example(written in python 3), 50% transparency :

hex(round(256*0.50))

:)

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set focus on an input field after rendering?

@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=...

Note that in jsx it's autoFocus (capital F) unlike plain old html which is case-insensitive.

Replace all occurrences of a string in a data frame

Here is a dplyr solution

library(dplyr)
library(stringr)

Censor_consistently <-  function(x){
  str_replace(x, '^\\s*([<>])\\s*(\\d+)', '\\1\\2')
}


test_df <- tibble(x = c('0.001', '<0.002', ' < 0.003', ' >  100'),  y = 4:1)

mutate_all(test_df, funs(Censor_consistently))

# A tibble: 4 × 2
x     y
<chr> <chr>
1  0.001     4
2 <0.002     3
3 <0.003     2
4   >100     1

Find the last element of an array while using a foreach loop in PHP

For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.

The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :

$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
    $some_item=$arr[$i];
    $i++;
}
$last_item=$arr[$i];
$i++;

A little homemade benchmark showed the following:

test1: 100000 runs of model morg

time: 1869.3430423737 milliseconds

test2: 100000 runs of model if last

time: 3235.6359958649 milliseconds

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How to print star pattern in JavaScript in a very simple manner?

for (var line = "#"; line.length < 8; line += "#")
console.log(line);

String delimiter in string.split method

String[] splitArray = subjectString.split("\\|\\|");

You use a function:

public String[] stringSplit(String string){

    String[] splitArray = string.split("\\|\\|");
    return splitArray;
}

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How to convert an NSString into an NSNumber

Use an NSNumberFormatter:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.

How to detect if a browser is Chrome using jQuery?

When I test the answer @IE, I got always "true". The better way is this which works also @IE:

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

As described in this answer: https://stackoverflow.com/a/4565120/1201725

How do you count the number of occurrences of a certain substring in a SQL varchar?

The first way that comes to mind is to do it indirectly by replacing the comma with an empty string and comparing the lengths

Declare @string varchar(1000)
Set @string = 'a,b,c,d'
select len(@string) - len(replace(@string, ',', ''))

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

An established connection was aborted by the software in your host machine

  1. Close Eclipse
  2. Open Task Manager and kill adb.exe
  3. Start Eclipse It should work.

How to get current timestamp in milliseconds since 1970 just the way Java gets

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}

Most useful NLog configurations

Logging different levels depending on whether or not there is an error

This example allows you to get more information when there is an error in your code. Basically, it buffers messages and only outputs those at a certain log level (e.g. Warn) unless a certain condition is met (e.g. there has been an error, so the log level is >= Error), then it will output more info (e.g. all messages from log levels >= Trace). Because the messages are buffered, this lets you gather trace information about what happened before an Error or ErrorException was logged - very useful!

I adapted this one from an example in the source code. I was thrown at first because I left out the AspNetBufferingWrapper (since mine isn't an ASP app) - it turns out that the PostFilteringWrapper requires some buffered target. Note that the target-ref element used in the above-linked example cannot be used in NLog 1.0 (I am using 1.0 Refresh for a .NET 4.0 app); it is necessary to put your target inside the wrapper block. Also note that the logic syntax (i.e. greater-than or less-than symbols, < and >) has to use the symbols, not the XML escapes for those symbols (i.e. &gt; and &lt;) or else NLog will error.

app.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
    </configSections>

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
        <variable name="appTitle" value="My app"/>
        <variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>

        <targets async="true">
            <!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
            <wrapper-target xsi:type="BufferingWrapper" name="smartLog">
                <wrapper-target xsi:type="PostFilteringWrapper">
                    <!--<target-ref name="fileAsCsv"/>-->
                    <target xsi:type="File" fileName="${csvPath}"
                    archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
                    >
                        <layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
                            <column name="time" layout="${longdate}" />
                            <column name="level" layout="${level:upperCase=true}"/>
                            <column name="message" layout="${message}" />
                            <column name="callsite" layout="${callsite:includeSourcePath=true}" />
                            <column name="stacktrace" layout="${stacktrace:topFrames=10}" />
                            <column name="exception" layout="${exception:format=ToString}"/>
                            <!--<column name="logger" layout="${logger}"/>-->
                        </layout>
                    </target>

                     <!--during normal execution only log certain messages--> 
                    <defaultFilter>level >= LogLevel.Warn</defaultFilter>

                     <!--if there is at least one error, log everything from trace level--> 
                    <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
                </wrapper-target>
            </wrapper-target>

        </targets>

        <rules>
            <logger name="*" minlevel="Trace" writeTo="smartLog"/>
        </rules>
    </nlog>
</configuration>

Angular + Material - How to refresh a data source (mat-table)

You can easily update the data of the table using "concat":

for example:

language.component.ts

teachDS: any[] = [];

language.component.html

<table mat-table [dataSource]="teachDS" class="list">

And, when you update the data (language.component.ts):

addItem() {
    // newItem is the object added to the list using a form or other way
    this.teachDS = this.teachDS.concat([newItem]);
 }

When you're using "concat" angular detect the changes of the object (this.teachDS) and you don't need to use another thing.

PD: It's work for me in angular 6 and 7, I didn't try another version.

Generating a PDF file from React Components

You can use ReactPDF

Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

Convert a 1D array to a 2D array in numpy

Try something like:

B = np.reshape(A,(-1,ncols))

You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.

Why is there no ForEach extension method on IEnumerable?

@Coincoin

The real power of the foreach extension method involves reusability of the Action<> without adding unnecessary methods to your code. Say that you have 10 lists and you want to perform the same logic on them, and a corresponding function doesn't fit into your class and is not reused. Instead of having ten for loops, or a generic function that is obviously a helper that doesn't belong, you can keep all of your logic in one place (the Action<>. So, dozens of lines get replaced with

Action<blah,blah> f = { foo };

List1.ForEach(p => f(p))
List2.ForEach(p => f(p))

etc...

The logic is in one place and you haven't polluted your class.

MySQL ORDER BY multiple column ASC and DESC

i think u miss understand about table relation..

users : scores = 1 : *

just join is not a solution.

is this your intention?

SELECT users.username, avg(scores.point), avg(scores.avg_time)
FROM scores, users
WHERE scores.user_id = users.id
GROUP BY users.username
ORDER BY avg(scores.point) DESC, avg(scores.avg_time)
LIMIT 0, 20

(this query to get each users average point and average avg_time by desc point, asc )avg_time

if you want to get each scores ranking? use left outer join

SELECT users.username, scores.point, scores.avg_time
FROM scores left outer join users on scores.user_id = users.id
ORDER BY scores.point DESC, scores.avg_time
LIMIT 0, 20

Error type 3 Error: Activity class {} does not exist

None of the above worked for me. I had a version of the app on the device that could not be uninstalled as it was corrupt somehow. I had to factory reset the device. Not too bothered cause it was a just a dev device

How to show text in combobox when no item selected?

Unfortunately none of the above worked for me, so instead I added a label on top of the comboxbox that says "Please select". I used the following code to show and hide it:

  1. When I initialise my combobox, if there is no selected value I bring it to the front and set the text:

    PleaseSelectValueLabel.BringToFront();
    PleaseSelectValueLabel.Text = Constants.AssessmentValuePrompt;
    
  2. If there is a value selected I send it to the back:

    PleaseSelectValueLabel.SendToBack();
    
  3. I then use the following events to move the label to the front or back depending on whether the user has selected a value:

    private void PleaseSelectValueLabel_Click(object sender, EventArgs e)
    {
        PleaseSelectValueLabel.SendToBack();
        AssessmentValue.Focus();
    }
    
    private void AssessmentValue_Click(object sender, EventArgs e)
    {
        PleaseSelectValueLabel.SendToBack();
    }
    
    //if the user hasnt selected an item, make the please select label visible again
    private void AssessmentValue_Leave(object sender, EventArgs e)
    {
        if (AssessmentValue.SelectedIndex < 0)
        {
            PleaseSelectValueLabel.BringToFront();
        }
    }
    

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

SQL Server: UPDATE a table by using ORDER BY

No.

Not a documented 100% supported way. There is an approach sometimes used for calculating running totals called "quirky update" that suggests that it might update in order of clustered index if certain conditions are met but as far as I know this relies completely on empirical observation rather than any guarantee.

But what version of SQL Server are you on? If SQL2005+ you might be able to do something with row_number and a CTE (You can update the CTE)

With cte As
(
SELECT id,Number,
ROW_NUMBER() OVER (ORDER BY id DESC) AS RN
FROM Test
)
UPDATE cte SET Number=RN

How to reduce the image size without losing quality in PHP

I'd go for jpeg. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick

Hope this helps

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                popuMenu.inflate(R.menu.bottom_nav_menu);
                popuMenu.show();
            }
        },100);

selected value get from db into dropdown select box option using php mysql error

You can also do like this ....

<?php  $countryname = $all_meta_for_user['country']; ?>

<select id="mycountry"  name="country" class="user">

    <?php $myrows = $wpdb->get_results( "SELECT * FROM wp_countries order by country_name" );
    foreach($myrows as $rows){
        if( $countryname == $rows->id ){ 
            echo "<option selected = 'selected' value='".$rows->id."'>".$rows->country_name."</option>";
        } else{ 
            echo "<option value='".$rows->id."'>".$rows->country_name."</option>";
        }
    }
    ?>
</select>

How do you serialize a model instance in Django?

ville = UneVille.objects.get(nom='lihlihlihlih')
....
blablablab
.......

return HttpResponse(simplejson.dumps(ville.__dict__))

I return the dict of my instance

so it return something like {'field1':value,"field2":value,....}

could not access the package manager. is the system running while installing android application

You can avoid the error by setting default device before launching application. Launch the AVD before starting the app.

In Visual Studio Code How do I merge between two local branches?

I found this extension for VS code called Git Merger. It adds Git: Merge from to the commands.

how to add new <li> to <ul> onclick with javascript

You were almost there:

You just need to append the li to ul and voila!

So just add

ul.appendChild(li);

to the end of your function so the end function will be like this:

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Element 4"));
  ul.appendChild(li);
}

Is it wrong to place the <script> tag after the </body> tag?

Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.

Browsers may perform error recovery, but you should never depend on that.

Hibernate Union alternatives

You could use id in (select id from ...) or id in (select id from ...)

e.g. instead of non-working

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

you could do

from Person p 
  where p.id in (select p1.id from Person p1 where p1.name="Joe") 
    or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

At least using MySQL, you will run into performance problems with it later, though. It's sometimes easier to do a poor man's join on two queries instead:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

It's often better to do two simple queries than one complex one.

EDIT:

to give an example, here is the EXPLAIN output of the resulting MySQL query from the subselect solution:

mysql> explain 
  select p.* from PERSON p 
    where p.id in (select p1.id from PERSON p1 where p1.name = "Joe") 
      or p.id in (select p2.id from PERSON p2 
        join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: a
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 247554
        Extra: Using where
*************************** 2. row ***************************
           id: 3
  select_type: DEPENDENT SUBQUERY
        table: NULL
         type: NULL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: a1
         type: unique_subquery
possible_keys: PRIMARY,name,sortname
          key: PRIMARY
      key_len: 4
          ref: func
         rows: 1
        Extra: Using where
3 rows in set (0.00 sec)

Most importantly, 1. row doesn't use any index and considers 200k+ rows. Bad! Execution of this query took 0.7s wheres both subqueries are in the milliseconds.

PHP code to convert a MySQL query to CSV

An update to @jrgns (with some slight syntax differences) solution.

$result = mysql_query('SELECT * FROM `some_table`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="export.csv"');
       header('Pragma: no-cache');    
       header('Expires: 0');
       fputcsv($fp, $headers); 
       while ($row = mysql_fetch_row($result)) 
       {
          fputcsv($fp, array_values($row)); 
       }
die; 
} 

cordova Android requirements failed: "Could not find an installed version of Gradle"

I m using Cordova version 7.0.1 and Cordova android version is 6.2.3. I was facing the issue while performing android build. I m using only Cordova CLI and not using android studio at all.

The quick workaround for this issue before its official fixed in Cordova is as follows:

  1. Look for check_reqs.js file under platforms\android\cordova\lib folder
  2. Edit the else part of androidStudioPath variable null check in get_gradle_wrapper function as below:

Existing code:

else { //OK, let's try to check for Gradle! return forgivingWhichSync('gradle'); }

Modified code:

else { //OK, let's try to check for Gradle! var sdkDir = process.env['ANDROID_HOME']; return path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper', 'gradlew'); }

NOTE: This change needs to be done everytime when the android platform is removed and re-added

UPDATE: In my case, I already had gradle wrapper inside my android SDK and I dint find necessity to install gradle explicitly. Hence, I made this workaround to minimize my impact and effort

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Make use of Arrow functions it improves the readability of code. No need to return anything in API.fetchComments, Api call is asynchronous when the request is completed then will get the response, there you have to just dispatch type and data.

Below code does the same job by making use of Arrow functions.

export const bindComments = postId => {
  return dispatch => {
    API.fetchComments(postId).then(comments => {
      dispatch({
        type: BIND_COMMENTS,
        comments,
        postId
      });
    });
  };
};

How to validate domain name in PHP?

Regular expression is the most effective way of checking for a domain validation. If you're dead set on not using a Regular Expression (which IMO is stupid), then you could split each part of a domain:

  • www. / sub-domain
  • domain name
  • .extension

You would then have to check each character in some sort of a loop to see that it matches a valid domain.

Like I said, it's much more effective to use a regular expression.

Rank function in MySQL

Combination of Daniel's and Salman's answer. However the rank will not give as continues sequence with ties exists . Instead it skips the rank to next. So maximum always reach row count.

    SELECT    first_name,
              age,
              gender,
              IF(age=@_last_age,@curRank:=@curRank,@curRank:=@_sequence) AS rank,
              @_sequence:=@_sequence+1,@_last_age:=age
    FROM      person p, (SELECT @curRank := 1, @_sequence:=1, @_last_age:=0) r
    ORDER BY  age;

Schema and Test Case:

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9, 'Kamal', 25, 'M');
INSERT INTO person VALUES (10, 'Saman', 32, 'M');

Output:

+------------+------+--------+------+--------------------------+-----------------+
| first_name | age  | gender | rank | @_sequence:=@_sequence+1 | @_last_age:=age |
+------------+------+--------+------+--------------------------+-----------------+
| Kathy      |   18 | F      |    1 |                        2 |              18 |
| Jane       |   20 | F      |    2 |                        3 |              20 |
| Nick       |   22 | M      |    3 |                        4 |              22 |
| Kamal      |   25 | M      |    4 |                        5 |              25 |
| Anne       |   25 | F      |    4 |                        6 |              25 |
| Bob        |   25 | M      |    4 |                        7 |              25 |
| Jack       |   30 | M      |    7 |                        8 |              30 |
| Bill       |   32 | M      |    8 |                        9 |              32 |
| Saman      |   32 | M      |    8 |                       10 |              32 |
| Steve      |   36 | M      |   10 |                       11 |              36 |
+------------+------+--------+------+--------------------------+-----------------+

Creating a constant Dictionary in C#

This is the closest thing you can get to a "CONST Dictionary":

public static int GetValueByName(string name)
{
    switch (name)
    {
        case "bob": return 1;
        case "billy": return 2;
        default: return -1;
    }
}

The compiler will be smart enough to build the code as clean as possible.

Spark Dataframe distinguish columns with duplicated name

Lets start with some data:

from pyspark.mllib.linalg import SparseVector
from pyspark.sql import Row

df1 = sqlContext.createDataFrame([
    Row(a=107831, f=SparseVector(
        5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
    Row(a=125231, f=SparseVector(
        5, {0: 0.0, 1: 0.0, 2: 0.0047, 3: 0.0, 4: 0.0043})),
])

df2 = sqlContext.createDataFrame([
    Row(a=107831, f=SparseVector(
        5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
    Row(a=107831, f=SparseVector(
        5, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0})),
])

There are a few ways you can approach this problem. First of all you can unambiguously reference child table columns using parent columns:

df1.join(df2, df1['a'] == df2['a']).select(df1['f']).show(2)

##  +--------------------+
##  |                   f|
##  +--------------------+
##  |(5,[0,1,2,3,4],[0...|
##  |(5,[0,1,2,3,4],[0...|
##  +--------------------+

You can also use table aliases:

from pyspark.sql.functions import col

df1_a = df1.alias("df1_a")
df2_a = df2.alias("df2_a")

df1_a.join(df2_a, col('df1_a.a') == col('df2_a.a')).select('df1_a.f').show(2)

##  +--------------------+
##  |                   f|
##  +--------------------+
##  |(5,[0,1,2,3,4],[0...|
##  |(5,[0,1,2,3,4],[0...|
##  +--------------------+

Finally you can programmatically rename columns:

df1_r = df1.select(*(col(x).alias(x + '_df1') for x in df1.columns))
df2_r = df2.select(*(col(x).alias(x + '_df2') for x in df2.columns))

df1_r.join(df2_r, col('a_df1') == col('a_df2')).select(col('f_df1')).show(2)

## +--------------------+
## |               f_df1|
## +--------------------+
## |(5,[0,1,2,3,4],[0...|
## |(5,[0,1,2,3,4],[0...|
## +--------------------+

Styling multi-line conditions in 'if' statements?

This doesn't improve so much but...

allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I had the duplicit definition of connection string in my WCF service. I was able to debug the service and to see the inner error message (not displayed by default):

ConfigurationErrorsException: The entry 'xxxEntities' has 
already been added. (C:\Users\WcfService\web.config line 35). 

which was after web.config transformation (note duplicit values)

<connectionStrings>
    <add name="xxxEntities" connectionString="metadata=res://*/ ...
    <add name="xxxEntities" connectionString="metadata=res://*/ ...

Hence removing unwanted connection string solved my problem.

Find integer index of rows with NaN in pandas dataframe

Let the dataframe be named df and the column of interest(i.e. the column in which we are trying to find nulls) is 'b'. Then the following snippet gives the desired index of null in the dataframe:

   for i in range(df.shape[0]):
       if df['b'].isnull().iloc[i]:
           print(i)

denied: requested access to the resource is denied : docker

I really hope this helps somebody (who looks to the final answers first as myself):

I continuously tried to type in

docker push user/repo/tag

Instead

docker push user/repo:tag

Since I also made my tag like this:

docker tag image user/repo/tag

...all hell broke lose.

I sincirely hope you don't repeat my mistake. I wasted like 30 mins on this...

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

MySQL vs MongoDB 1000 reads

man,,, the answer is that you're basically testing PHP and not a database.

don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.

   foreach ($cursor as $obj)
    {
        //echo $obj["thread_title"] . "<br><Br>";
    }

while the other chunk is spend yacking up a bunch of rand numbers.

function get_15_random_numbers()
{
    $numbers = array();
    for($i=1;$i<=15;$i++)
    {
        $numbers[] = mt_rand(1, 20000000) ;

    }
    return $numbers;
}

then theres a major difference b/w implode and in.

and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.

$m = new Mongo();

vs

$db = new AQLDatabase();

so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.

urghhh.

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

How to hide status bar in Android

Use theme "Theme.NoTitleBar.Fullscreen" and try setting "android:windowSoftInputMode=adjustResize" for the activity in AndroidManifest.xml. You can find details here.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

The target principal name is incorrect. Cannot generate SSPI context

In my Case since I was working in my development environment, someone had shut down the Domain Controller and Windows Credentials couldn't be authenticated. After turning on the Domain Controller, the error disappeared and everything worked just fine.

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

Display text on MouseOver for image in html

You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?

CSS:

div {
    display: none;
    border:1px solid #000;
    height:30px;
    width:290px;
    margin-left:10px;
}

a:hover + div {
    display: block;
}?

How can I show dots ("...") in a span with hidden overflow?

I think you are looking for text-overflow: ellipsis in combination with white-space: nowrap

See some more details here

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

How To Save Canvas As An Image With canvas.toDataURL()?

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

Difference between $.ajax() and $.get() and $.load()

$.get = $.ajax({type: 'GET'});

$.load() is a helper function which only can be invoked on elements.

$.ajax() gives you most control. you can specify if you want to POST data, got more callbacks etc.

Delete empty rows

I believe that your problem is that you're checking for an empty string using double quotes instead of single quotes. Try just changing to:

DELETE FROM table WHERE edit_user=''

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

Jenkins/Hudson - accessing the current build number?

Jenkins Pipeline also provides the current build number as the property number of the currentBuild. It can be read as currentBuild.number.

For example:

// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"

Other properties of currentBuild are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

Pure CSS multi-level drop-down menu

For a menu which responds to click events as opposed to just hover, and acts in a similar way to a select control...

Pure CSS Select Menu

HTML

<ul tabindex='0'>
    <li>
        <input id='item1' type='radio' name='item' checked='true' />
        <label for='item1'>Item 1</label>
    </li>
    <li>
        <input id='item2' type='radio' name='item' />
        <label for='item2'>Item 2</label>
    </li>
    <li>
        <input id='item3' type='radio' name='item' />
        <label for='item3'>Item 3</label>
    </li>
</ul>

CSS

ul, li {
    list-style:none;
    margin:0;
    padding:0;
}
li input {
    display:none;
}
ul:not(:focus) input:not(:checked), ul:not(:focus) input:not(:checked) + label {
    display:none;
}
input:checked+label {
    color:red;
}

How do I find the MySQL my.cnf location

All great suggestions, in my case I didn't find it in any of those locations, but in /usr/share/mysql, I have a RHEL VM and I installed mysql5.5

Mock functions in Go

Personally, I don't use gomock (or any mocking framework for that matter; mocking in Go is very easy without it). I would either pass a dependency to the downloader() function as a parameter, or I would make downloader() a method on a type, and the type can hold the get_page dependency:

Method 1: Pass get_page() as a parameter of downloader()

type PageGetter func(url string) string

func downloader(pageGetterFunc PageGetter) {
    // ...
    content := pageGetterFunc(BASE_URL)
    // ...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    downloader(get_page)
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader(t *testing.T) {
    downloader(mock_get_page)
}

Method2: Make download() a method of a type Downloader:

If you don't want to pass the dependency as a parameter, you could also make get_page() a member of a type, and make download() a method of that type, which can then use get_page:

type PageGetter func(url string) string

type Downloader struct {
    get_page PageGetter
}

func NewDownloader(pg PageGetter) *Downloader {
    return &Downloader{get_page: pg}
}

func (d *Downloader) download() {
    //...
    content := d.get_page(BASE_URL)
    //...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    d := NewDownloader(get_page)
    d.download()
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader() {
    d := NewDownloader(mock_get_page)
    d.download()
}

Android : How to read file in bytes?

A simple InputStream will do

byte[] fileToBytes(File file){
    byte[] bytes = new byte[0];
    try(FileInputStream inputStream = new FileInputStream(file)) {
        bytes = new byte[inputStream.available()];
        //noinspection ResultOfMethodCallIgnored
        inputStream.read(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

fatal: 'origin' does not appear to be a git repository

I had the same error on git pull origin branchname when setting the remote origin as path fs and not ssh in .git/config:

fatal: '/path/to/repo.git' does not appear to be a git repository 
fatal: The remote end hung up unexpectedly

It was like so (this only works for users on same server of git that have access to git):

url = file:///path/to/repo.git/

Fixed it like so (this works on all users that have access to git user (ssh authorizes_keys or password)):

url = [email protected]:path/to/repo.git

the reason I had it as a directory path was because the git files are on the same server.

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

Why and how to fix? IIS Express "The specified port is in use"

I had same error showing up. I had my web service set as an application in IIS and I fixed it by:

Right-click on my WebService project inside my solution > Properties > Web > Under 'Servers' change from IIS Express to Local IIS (it will automatically create a Virtual Directory which is what you want)

How to display a list inline using Twitter's Bootstrap

According to Bootstrap documentation of 2.3.2 and 3, the class should be defined like this:

Bootstrap 2.3.2

<ul class="inline">
  <li>...</li>
</ul>

Bootstrap 3

<ul class="list-inline">
  <li>...</li>
</ul>

Highlighting Text Color using Html.fromHtml() in Android?

First Convert your string into HTML then convert it into spannable. do as suggest the following codes.

 Spannable spannable = new SpannableString(Html.fromHtml(labelText));
                    
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

I use three flags to resolve the problem:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK | 
                Intent.FLAG_ACTIVITY_NEW_TASK);

Gradle build without tests

You will have to add -x test

e.g. ./gradlew build -x test

or

gradle build -x test

String to byte array in php

You could try this:

$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
    $hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);

What is the list of supported languages/locales on Android?

http://developer.android.com/reference/java/util/Locale.html

See CLDR for specific language support.

Ex : CLDR 1.8 for 2.3

http://cldr.unicode.org/index/downloads/cldr-1-8

Languages:

Afar [Qafar];
Afrikaans;
Akan;
Albanian [shqipe];
Amharic [????];
Arabic [?????????];
Armenian [???????];
Assamese [??????];
Asu [Kipare];
Atsam [cch];
Azerbaijani (Arabic) [az?rbaycanca (?r?b)];
Azerbaijani (Cyrillic) [?????????? (kiril)];
Azerbaijani (Latin) [az?rbaycanca (latin)];
Bambara [bamanakan];
Basque [euskara];
Belarusian [??????????];
Bemba [Ichibemba];
Bena [Hibena];
Bengali [?????];
Blin [???];
Bosnian [Bosanski];
Breton [br];
Bulgarian [?????????];
Burmese [???];
Catalan [català];
Central Morocco Tamazight (Latin) [Tamazi?t (Latn)];
Cherokee [???];
Chiga [Rukiga];
Colognian [ksh];
Cornish [kernewek];
Croatian [hrvatski];
Czech [ceština];
Danish [dansk];
Divehi [????????????];
Dutch [Nederlands];
Dzongkha [??????];
Embu [Kiembu];
English (Deseret) [ ()];
English (Shavian);
Esperanto;
Estonian [eesti];
Ewe [E?egbe];
Faroese [føroyskt];
Filipino;
Finnish [suomi];
French [français];
Friulian [furlan];
Fulah [Pulaar];
Ga [gaa];
Galician [galego];
Ganda [Luganda];
Geez [????];
Georgian [???????];
German [Deutsch];
Greek [????????];
Gujarati [???????];
Gusii [Ekegusii];
Hausa (Arabic) [Hausa (Arab)];
Hausa (Latin) [Hausa (Latn)];
Hawaiian [?olelo Hawai?i];
Hebrew [???????];
Hindi [??????];
Hungarian [magyar];
Icelandic [íslenska];
Igbo;
Indonesian [Bahasa Indonesia];
Interlingua;
Inuktitut [?????? ??????];
Irish [Gaeilge];
Italian [italiano];
Japanese [???];
Jju [kaj];
Kabuverdianu;
Kabyle [Taqbaylit];
Kalaallisut;
Kalenjin;
Kamba [Kikamba];
Kannada [?????];
Kazakh (Cyrillic) [????? (Cyrl)];
Khmer [?????????];
Kikuyu [Gikuyu];
Kinyarwanda;
Kirghiz [??????];
Konkani [??????];
Korean [???];
Koro [kfo];
Koyra Chiini [Koyra ciini];
Koyraboro Senni;
Kpelle [kpe];
Kurdish (Arabic) [?????? (??????)?];
Kurdish (Latin) [?kurdî (?????)?];
Langi [K?laangi];
Lao [???];
Latvian [latviešu];
Lingala [lingála];
Lithuanian [lietuviu];
Low German [Plattdüütsch];
Luo [Dholuo];
Luyia [Luluhia];
Macedonian [??????????];
Machame [Kimachame];
Makonde [Chimakonde];
Malagasy;
Malay [Bahasa Melayu];
Malayalam [??????];
Maltese [Malti];
Manx [Gaelg];
Maori [mi];
Marathi [?????];
Masai [Maa];
Meru [Kimiru];
Mongolian (Cyrillic) [?????? (Cyrl)];
Mongolian (Mongolian) [?????? (Mong)];
Morisyen [kreol morisien];
Nama [Khoekhoegowab];
Nepali [??????];
North Ndebele [isiNdebele];
Northern Sami [davvisámegiella];
Northern Sotho [Sesotho sa Leboa];
Norwegian [norsk];
Norwegian Bokmål [norsk bokmål];
Norwegian Nynorsk [nynorsk];
Nyanja [ny];
Nyankole [Runyankore];
Occitan;
Oriya [?????];
Oromo [Oromoo];
Pashto [??????];
Persian [???????];
Polish [polski];
Portuguese [português];
Punjabi (Arabic) [?????? (???????)?];
Punjabi (Gurmukhi) [?????? (???????)];
Romanian [româna];
Romansh [rumantsch];
Rombo [Kihorombo];
Russian [???????];
Rwa [Kiruwa];
Saho [ssy];
Samburu [Kisampur];
Sango [Sängö];
Sanskrit [??????? ????];
Sena;
Serbian (Cyrillic) [?????? (????????)];
Serbian (Latin) [Srpski (Latinica)];
Shambala [Kishambaa];
Shona [chiShona];
Sichuan Yi [???];
Sidamo [Sidaamu Afo];
Simplified Chinese [??(??)];
Sinhala [?????];
Slovak [slovencina];
Slovenian [slovenšcina];
Soga [Olusoga];
Somali [Soomaali];
South Ndebele [isiNdebele];
Southern Sotho [Sesotho];
Spanish [español];
Swahili [Kenya];
Swati [Siswati];
Swedish [svenska];
Swiss German [Schwiizertüütsch];
Syriac [????????];
Tachelhit (Latin) [tamazight (Latn)];
Tachelhit (Tifinagh) [???????? (Tfng)];
Tagalog;
Taita [Kitaita];
Tajik (Cyrillic) [tg (Cyrl)];
Tamil [?????];
Taroko [trv];
Tatar [?????];
Telugu [??????];
Teso [Kiteso];
Thai [???];
Tibetan [????????];
Tigre [???];
Tigrinya [????];
Tonga [lea fakatonga];
Traditional Chinese [????];
Tsonga [Xitsonga];
Tswana [Setswana];
Turkish [Türkçe];
Tyap [kcg];
Uighur (Arabic) [ug (Arab)];
Ukrainian [??????????];
Urdu [??????];
Uzbek (Arabic) [??????? (????)?];
Uzbek (Cyrillic) [????? (?????)];
Uzbek (Latin) [o'zbekcha (Lotin)];
Venda [Tshiven?a];
Vietnamese [Ti?ng Vi?t];
Vunjo [Kyivunjo];
Walamo [?????];
Welsh [Cymraeg];
Wolof (Latin) [wo (Latn)];
Xhosa [isiXhosa];
Yoruba [Èdè Yorùbá];
Zulu [isiZulu]

Locale IDs can be found in:

http://www.localeplanet.com/icu/

Steps to follow

Step 1 : Need to find which all Languages supported on Android

Sol - follow my above answer ie in cldr-1-8 Languages.

Step 2 : Since cldr-1-8 Languages does not give u Locale short form which is need to be found for desire language Sol - Once language is available in cldr-1-8 Languages list then check for the shortform in http://www.localeplanet.com/icu/ link

Example :For language Hindi [??????] (1)we need to search its present in cldr-1-8 language then (2)search for Hindi in http://www.localeplanet.com/icu/ for Locale id its comes out to be http://www.localeplanet.com/icu/hi/index.html this link and see Locale id from it .

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Change background color of R plot

One Google search later we've learned that you can set the entire plotting device background color as Owen indicates. If you just want the plotting region altered, you have to do something like what is outlined in that R-Help thread:

plot(df)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "gray")
points(df)

The barplot function has an add parameter that you'll likely need to use.

How do I return a string from a regex match in python?

Note that re.match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0) as the folks suggested.

How to start an application without waiting in a batch file?

I'm making a guess here, but your start invocation probably looks like this:

start "\Foo\Bar\Path with spaces in it\program.exe"

This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.

If you use start with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:

start "" "\Foo\Bar\Path with spaces in it\program.exe"

This is because start interprets the first quoted argument it finds as the window title for a new console window.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Using = causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:

HELLO = world
HELLO_WORLD = $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using := is similar to using =. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:

HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# Still echoes "world world!"
echo $(HELLO_WORLD)

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using ?= assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=), it is still considered set I think. Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=, it is expanded I think. The resulting value is expanded when it is used I think. For example:

HELLO_WORLD = hello
HELLO_WORLD += world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

Composer Warning: openssl extension is missing. How to enable in WAMP

I had the same problem even though openssl was enabled. The issue was that the Composer installer was looking at this config file:

C:\wamp\bin\php\php5.4.3\php.ini

But the config file that's loaded is actually here:

C:\wamp\bin\apache\apache2.2.22\bin\php.ini

So I just had to uncomment it in the first php.ini file and that did the trick. This is how WAMP was installed on my machine by default. I didn't go changing anything, so this will probably happen to others as well. This is basically the same as Augie Gardner's answer above, but I just wanted to point out that you might have two php.ini files.

Javascript Src Path

As your clock.js is in the root, put your code as this to call your javascript in the index.html found in the folders you mentioned.

<SCRIPT LANGUAGE="JavaScript" SRC="../clock.js"></SCRIPT>

This will call the clock.js which you put in the root of your web site.

Correct way to handle conditional styling in React

The best way to handle styling is by using classes with set of css properties.

example:

<Component className={this.getColor()} />

getColor() {
    let class = "badge m2";
    class += this.state.count===0 ? "warning" : danger;
    return class;
}

How to check how many letters are in a string in java?

To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

Android: how to convert whole ImageView to Bitmap?

This is a working code

imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

Cannot find module cv2 when using OpenCV

None of the above answers worked for me. I was going crazy until I found this solution below!

Simply run:

sudo apt install python-opencv

Initialize a string in C to empty string

I think Amarghosh answered correctly. If you want to Initialize an empty string(without knowing the size) the best way is:

//this will create an empty string without no memory allocation. 
char str[]="";// it is look like {0}

But if you want initialize a string with a fixed memory allocation you can do:

// this is better if you know your string size.    
char str[5]=""; // it is look like {0, 0, 0, 0, 0} 

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

Why AVD Manager options are not showing in Android Studio

The only thing that worked for me (with an existing project on a fresh install of macOS) was:

"File" > "Sync Project with Gradle Files"

This was odd to me since building the project succeeded with no errors or log messages, but I couldn’t run the project and there was nothing Android in the Tools menu.

I had already tried creating a new Android project and running that. It didn't help with my existing project.

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

How to change Windows 10 interface language on Single Language version

You can download language pack and use "Install or Uninstall display languages" wizard. To do this:

  • Press Win+R, paste lpksetup and press Enter
  • Wizard will appear on the screen
  • Click the Install display languages button
  • In the next page of the wizard, click Browse and pick the *.cab file of the MUI language you downloaded
  • Click the Next button to install language

How to downgrade Node version

This may be due to version incompatibility between your code and the version you have installed.

In my case I was using v8.12.0 for development (locally) and installed latest version v13.7.0 on the server.

So using nvm I switched the node version to v8.12.0 with the below command:

> nvm install 8.12.0 // to install the version I wanted

> nvm use 8.12.0  // use the installed version

NOTE: You need to install nvm on your system to use nvm.

You should try this solution before trying solutions like installing build-essentials or uninstalling the current node version because you could switch between versions easily than reverting all the installations/uninstallations that you've done.

error::make_unique is not a member of ‘std’

If you are stuck with c++11, you can get make_unique from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

How can I rename a single column in a table at select?

if you are using sql server, use brackets or single quotes around alias name in a query you have in code.

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

Spring MVC - HttpMediaTypeNotAcceptableException

For me the problem was the URL I was trying to access. I had url like this:

{{ip}}:{{port}}/{{path}}/person.html

When you end url with .html it means that you will not accept any other payload than html. I needed to remove .html from the end for my endpoint to work properly. (You can also append .json at the end of url and it will work too)

Additionally your url-pattern in web.xml need to be configured properly to allow you to access the resource. For me it is

<servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Previously I had *.html* and it was preventing me an access to the endpoint.

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

How do I apply a diff patch on Windows?

It appears that TortoiseSVN (TortoiseMerge) requires the line Index: foobar.py in the diff/patch file. This is what I needed to do to make a non-TortoiseSVN patch file work with TortoiseSVN's right-click Apply Patch command.

Before:

--- foobar.py.org   Sat May 08 16:00:56 2010
+++ foobar.py   Sat May 08 15:47:48 2010

After:

Index: foobar.py
===================================================================
--- foobar.py
+++ foobar.py   (working copy)

Or if you know the specific revision your contributor was working from:

Index: foobar.py
===================================================================
--- foobar.py   (revision 1157)
+++ foobar.py   (working copy)

Print directly from browser without print popup window

this.print(false);

I tried this in Chrome, Firefox and IE. It works only in Firefox and IE, it uses the default printer (with default print settings) and only works when I render a PDF (I use Foxit Reader with Safe Reading Mode disabled). Chrome shows the print dialog, also the other browsers when I render an HTML page.

Python variables as keys to dict

Based on the answer by mouad, here's a more pythonic way to select the variables based on a prefix:

# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666

prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
              for v in sourcedict
              if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}

You can even put that in a function with prefix and sourcedict as arguments.

Python AttributeError: 'module' object has no attribute 'Serial'

You're importing the module, not the class. So, you must write:

from serial import Serial

You need to install serial module correctly: pip install pyserial.

Is it bad practice to use break to exit a loop in Java?

While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.

Is there a way to use max-width and height for a background image?

As thirtydot said, you can use the CSS3 background-size syntax:

For example:

-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;

However, as also stated by thirtydot, this does not work in IE6, 7 and 8.

See the following links for more information about background-size: http://www.w3.org/TR/css3-background/#the-background-size

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

This happened to me after I installed Visual Studio 15 2017.

The C++ compiler for Visual Studio 14 2015 was not the problem. It seemed to be a problem with the Windows 10 SDK.

Adding the Windows 10 SDKs to Visual Studio 14 2015 solved the problem for me.

See attached screenshot.

Enter image description here

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

How can I create a link to a local file on a locally-run web page?

I've a way and work like this:

<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>

How to create a template function within a class? (C++)

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

How to check if a variable is equal to one string or another string?

Two separate checks. Also, use == rather than is to check for equality rather than identity.

 if var=='stringone' or var=='stringtwo':
     dosomething()

How do I create a self-signed certificate for code signing on Windows?

Roger's answer was very helpful.

I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with

certutil -addstore Root Demo_CA.cer

which Roger's answer didn't quite cover.

Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).

REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.

PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64

makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
   -a sha256 -cy authority -sky signature ^
   -sv Demo_CA.pvk Demo_CA.cer

makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
   -sky signature ^
   -ic Demo_CA.cer -iv Demo_CA.pvk ^
   -sv Demo_SPC.pvk Demo_SPC.cer

pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
   -pfx Demo_SPC.pfx ^
   -po x

inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v

signtool sign /d "description" /du "www.yoyodyne.com" ^
   /f Demo_SPC.pfx ^
   /p x ^
   /v driver\demoprinter.cat

certutil -addstore Root Demo_CA.cer

rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F

rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F

certutil -delstore Root Demo_CA

Regular expression to match a line that doesn't contain a word

If you want to match a character to negate a word similar to negate character class:

For example, a string:

<?
$str="aaa        bbb4      aaa     bbb7";
?>

Do not use:

<?
preg_match('/aaa[^bbb]+?bbb7/s', $str, $matches);
?>

Use:

<?
preg_match('/aaa(?:(?!bbb).)+?bbb7/s', $str, $matches);
?>

Notice "(?!bbb)." is neither lookbehind nor lookahead, it's lookcurrent, for example:

"(?=abc)abcde", "(?!abc)abcde"

How do I convert csv file to rdd

A simplistic approach would be to have a way to preserve the header.

Let's say you have a file.csv like:

user, topic, hits
om,  scala, 120
daniel, spark, 80
3754978, spark, 1

We can define a header class that uses a parsed version of the first row:

class SimpleCSVHeader(header:Array[String]) extends Serializable {
  val index = header.zipWithIndex.toMap
  def apply(array:Array[String], key:String):String = array(index(key))
}

That we can use that header to address the data further down the road:

val csv = sc.textFile("file.csv")  // original file
val data = csv.map(line => line.split(",").map(elem => elem.trim)) //lines in rows
val header = new SimpleCSVHeader(data.take(1)(0)) // we build our header with the first line
val rows = data.filter(line => header(line,"user") != "user") // filter the header out
val users = rows.map(row => header(row,"user")
val usersByHits = rows.map(row => header(row,"user") -> header(row,"hits").toInt)
...

Note that the header is not much more than a simple map of a mnemonic to the array index. Pretty much all this could be done on the ordinal place of the element in the array, like user = row(0)

PS: Welcome to Scala :-)

Checking for duplicate strings in JavaScript array

Here's my solution if you are using typescript in a functional way:

const hasDuplicates = <T>(arr: T[]): boolean => {
  if (arr.length === 0) return false
  if (arr.lastIndexOf(arr[0]) !== 0) return true
  return hasDuplicates(arr.slice(1))
}

jQuery Mobile - back button

Newer versions of JQuery mobile API (I guess its newer than 1.5) require adding 'back' button explicitly in header or bottom of each page.

So, try adding this in your page div tags:

data-add-back-btn="true"
data-back-btn-text="Back"

Example:

<div data-role="page" id="page2" data-add-back-btn="true" data-back-btn-text="Back">

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

Run jQuery function onclick

You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.

$("div.system_box").on('mouseenter', function(){
    //enter
})
.on('mouseleave', function(){
    //leave
});

fiddle

note: do not use hover as that is deprecated

An App ID with Identifier '' is not available. Please enter a different string

I had the same problem, when I use Xcode7.3 it. I solved the problem: I created a new profile select Ad Hoc, and then downloaded to Xcode.That‘s OK!

enter image description here

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

Set angular scope variable in markup

I like the answer but I think it would be better that you create a global scope function that will allow you to set the scope variable needed.

So in the globalController create

$scope.setScopeVariable = function(variable, value){
    $scope[variable] = value;
}

and then in your html file call it

{{setScopeVariable('myVar', 'whatever')}}

This will then allow you to use $scope.myVar in your respective controller

How to install the Six module in Python2.7

here's what six is:

pip search six
six                       - Python 2 and 3 compatibility utilities

to install:

pip install six

though if you did install python-dateutil from pip six should have been set as a dependency.

N.B.: to install pip run easy_install pip from command line.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Well if you know the order of your words.. you can use:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'

Also you can use:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

How to find the size of integer array

_msize(array) in Windows or malloc_usable_size(array) in Linux should work for the dynamic array

Both are located within malloc.h and both return a size_t

Can you 'exit' a loop in PHP?

All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break all together.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
    $val = $arr[$i];
    if ($val == 'stop') {
        $found = true; // this will cause the code to 
                       // stop looping the next time 
                       // the condition is checked
    }
    echo "$val<br />\n";
}

I consider this to be better code practice because it does not rely on the scope that break is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.

Filter Java Stream to 1 and only 1 element

Update

Nice suggestion in comment from @Holger:

Optional<User> match = users.stream()
              .filter((user) -> user.getId() > 1)
              .reduce((u, v) -> { throw new IllegalStateException("More than one ID found") });

Original answer

The exception is thrown by Optional#get, but if you have more than one element that won't help. You could collect the users in a collection that only accepts one item, for example:

User match = users.stream().filter((user) -> user.getId() > 1)
                  .collect(toCollection(() -> new ArrayBlockingQueue<User>(1)))
                  .poll();

which throws a java.lang.IllegalStateException: Queue full, but that feels too hacky.

Or you could use a reduction combined with an optional:

User match = Optional.ofNullable(users.stream().filter((user) -> user.getId() > 1)
                .reduce(null, (u, v) -> {
                    if (u != null && v != null)
                        throw new IllegalStateException("More than one ID found");
                    else return u == null ? v : u;
                })).get();

The reduction essentially returns:

  • null if no user is found
  • the user if only one is found
  • throws an exception if more than one is found

The result is then wrapped in an optional.

But the simplest solution would probably be to just collect to a collection, check that its size is 1 and get the only element.

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

You are converting cert into BKS Keystore, why aren't you using .cert directly, from https://developer.android.com/training/articles/security-ssl.html:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
    ca = cf.generateCertificate(instream);
} finally {
    caInput.close();
}

KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

okHttpClient.setSslSocketFactory(context.getSocketFactory());

How to Sign an Already Compiled Apk

fastest way is by signing with the debug keystore:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android

or on Windows:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

this is more likely happening because somewhere along your certificate chain you have a certificate, more likely an old root, which is still signed with the MD2RSA algorythm.

You need to locate it into your certificate store and delete it.

Then get back to your certification authority and ask them for then new root.

It will more likely be the same root with the same validity period but it has been recertified with SHA1RSA.

Hope this help.

JAXB :Need Namespace Prefix to all the elements

MSK,

Have you tried setting a namespace declaration to your member variables like this? :

@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;

@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;

For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Getting "conflicting types for function" in C, why?

This often happens when you modify a c function definition and forget to update the corresponding header definition.

Is it possible to select the last n items with nth-child?

nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';
    });
}

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.

eg.:

function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';
    chut.appendChild(log);
    chut.appendChild(textarea);
    chut.appendChild(input);
    chut.appendChild(button);
    document.getElementById('chuts').appendChild(chut);

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);
    };

    return chut;
}

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.

ETA:

I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};
...

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);
}

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

How to restore PostgreSQL dump file into Postgres databases?

You might need to set permissions at the database level that allows your schema owner to restore the dump.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

Select the project in Project Explorer, right-click and select Properties -> Java Build Path -> Source -> Check the box for Allow output folders for source folders

Saving a Numpy array as an image

If you are working in python environment Spyder, then it cannot get more easier than to just right click the array in variable explorer, and then choose Show Image option.

enter image description here

This will ask you to save image to dsik, mostly in PNG format.

PIL library will not be needed in this case.

Run a vbscript from another vbscript

You can also load the body of the script and execute it within the same process:

Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile("script2.vbs")
body = ts.ReadAll
ts.Close
Execute body

How can I get the current page name in WordPress?

Ok, you must grab the page title before the loop.

$page_title = $wp_query->post->post_title;

Check for the reference: http://codex.wordpress.org/Function_Reference/WP_Query#Properties.

Do a

print_r($wp_query)

before the loop to see all the values of the $wp_query object.

M_PI works with math.h but not with cmath in Visual Studio

Consider adding the switch /D_USE_MATH_DEFINES to your compilation command line, or to define the macro in the project settings. This will drag the symbol to all reachable dark corners of include and source files leaving your source clean for multiple platforms. If you set it globally for the whole project, you will not forget it later in a new file(s).

NVIDIA NVML Driver/library version mismatch

So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:

[   10.118255] NVRM: API mismatch: the client has the version 410.79, but
           NVRM: this kernel module has the version 384.130.  Please
           NVRM: make sure that this kernel module and all NVIDIA driver
           NVRM: components have the same version.

However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:

# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot

And then it worked.

After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers

I recommend using the locate command (not installed by default) rather than searching the filesystem every time.

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

getMinutes() 0-9 - How to display two digit numbers?

you should check if it is less than 10... not looking for the length of it , because this is a number and not a string

Exists Angularjs code/naming conventions?

Check out this GitHub repository that describes best practices for AngularJS apps. It has naming conventions for different components. It is not complete, but it is community-driven so everyone can contribute.

Programmatically get own phone number in iOS

No official API to do it. Using private API you can use following method:

-(NSString*) getMyNumber {
    NSLog(@"Open CoreTelephony");
    void *lib = dlopen("/Symbols/System/Library/Framework/CoreTelephony.framework/CoreTelephony",RTLD_LAZY);
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
    NSString* (*pCTSettingCopyMyPhoneNumber)() = dlsym(lib, "CTSettingCopyMyPhoneNumber");
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");

    if (pCTSettingCopyMyPhoneNumber == nil) {
        NSLog(@"pCTSettingCopyMyPhoneNumber is nil");
        return nil;
    }
    NSString* ownPhoneNumber = pCTSettingCopyMyPhoneNumber();
    dlclose(lib);
    return ownPhoneNumber;
}

It works on iOS 6 without JB and special signing.

As mentioned creker on iOS 7 with JB you need to use entitlements to make it working.

How to do it with entitlements you can find here: iOS 7: How to get own number via private API?

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers

Session variables in ASP.NET MVC

The answer here is correct, I however struggled to implement it in an ASP.NET MVC 3 app. I wanted to access a Session object in a controller and couldn't figure out why I kept on getting a "Instance not set to an instance of an Object error". What I noticed is that in a controller when I tried to access the session by doing the following, I kept on getting that error. This is due to the fact that this.HttpContext is part of the Controller object.

this.Session["blah"]
// or
this.HttpContext.Session["blah"]

However, what I wanted was the HttpContext that's part of the System.Web namespace because this is the one the Answer above suggests to use in Global.asax.cs. So I had to explicitly do the following:

System.Web.HttpContext.Current.Session["blah"]

this helped me, not sure if I did anything that isn't M.O. around here, but I hope it helps someone!

Does JavaScript pass by reference?

Without purisms, I think that the best way to emulate scalar argument by reference in JavaScript is using object, like previous an answer tells.

However, I do a little bit different:

I've made the object assignment inside function call, so one can see the reference parameters near the function call. It increases the source readability.

In function declaration, I put the properties like a comment, for the very same reason: readability.

var r;

funcWithRefScalars(r = {amount:200, message:null} );
console.log(r.amount + " - " + r.message);


function funcWithRefScalars(o) {  // o(amount, message)
  o.amount  *= 1.2;
  o.message = "20% increase";
}

In the above example, null indicates clearly an output reference parameter.

The exit:

240 - 20% Increase

On the client-side, console.log should be replaced by alert.

? ? ?

Another method that can be even more readable:

var amount, message;

funcWithRefScalars(amount = [200], message = [null] );
console.log(amount[0] + " - " + message[0]);

function funcWithRefScalars(amount, message) {  // o(amount, message)
   amount[0]  *= 1.2;
   message[0] = "20% increase";
}

Here you don't even need to create new dummy names, like r above.

How do I find the caller of a method using stacktrace or reflection?

Java 9 - JEP 259: Stack-Walking API

JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. Before Stack-Walking API, common ways of accessing stack frames were:

Throwable::getStackTrace and Thread::getStackTrace return an array of StackTraceElement objects, which contain the class name and method name of each stack-trace element.

SecurityManager::getClassContext is a protected method, which allows a SecurityManager subclass to access the class context.

JDK-internal sun.reflect.Reflection::getCallerClass method which you shouldn't use anyway

Using these APIs are usually inefficient:

These APIs require the VM to eagerly capture a snapshot of the entire stack, and they return information representing the entire stack. There is no way to avoid the cost of examining all the frames if the caller is only interested in the top few frames on the stack.

In order to find the immediate caller's class, first obtain a StackWalker:

StackWalker walker = StackWalker
                           .getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

Then either call the getCallerClass():

Class<?> callerClass = walker.getCallerClass();

or walk the StackFrames and get the first preceding StackFrame:

walker.walk(frames -> frames
      .map(StackWalker.StackFrame::getDeclaringClass)
      .skip(1)
      .findFirst());

Publish to IIS, setting Environment Variable

Edit: as of RC2 and RTM releases, this advice is out of date. The best way I have found to accomplish this in release is to edit the following web.config sections in IIS for each environment:

system.webServer/aspNetCore:

Edit the environmentVariable entry and add an environment variable setting:

ASPNETCORE_ENVIRONMENT : < Your environment name >


As an alternative to drpdrp's approach, you can do the following:

  • In your project.json, add commands that pass the ASPNET_ENV variable directly to Kestrel:

    "commands": {
        "Development": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development",
        "Staging": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Staging",
        "Production": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Production"
    }
    
  • When publishing, use the --iis-command option to specify an environment:

    dnu publish --configuration Debug --iis-command Staging --out "outputdir" --runtime dnx-clr-win-x86-1.0.0-rc1-update1
    

I found this approach to be less intrusive than creating extra IIS users.

Difference between acceptance test and functional test?

In my world, we use the terms as follows:

functional testing: This is a verification activity; did we build a correctly working product? Does the software meet the business requirements?

For this type of testing we have test cases that cover all the possible scenarios we can think of, even if that scenario is unlikely to exist "in the real world". When doing this type of testing, we aim for maximum code coverage. We use any test environment we can grab at the time, it doesn't have to be "production" caliber, so long as it's usable.

acceptance testing: This is a validation activity; did we build the right thing? Is this what the customer really needs?

This is usually done in cooperation with the customer, or by an internal customer proxy (product owner). For this type of testing we use test cases that cover the typical scenarios under which we expect the software to be used. This test must be conducted in a "production-like" environment, on hardware that is the same as, or close to, what a customer will use. This is when we test our "ilities":

  • Reliability, Availability: Validated via a stress test.

  • Scalability: Validated via a load test.

  • Usability: Validated via an inspection and demonstration to the customer. Is the UI configured to their liking? Did we put the customer branding in all the right places? Do we have all the fields/screens they asked for?

  • Security (aka, Securability, just to fit in): Validated via demonstration. Sometimes a customer will hire an outside firm to do a security audit and/or intrusion testing.

  • Maintainability: Validated via demonstration of how we will deliver software updates/patches.

  • Configurability: Validated via demonstration of how the customer can modify the system to suit their needs.

This is by no means standard, and I don't think there is a "standard" definition, as the conflicting answers here demonstrate. The most important thing for your organization is that you define these terms precisely, and stick to them.

Retrieve WordPress root directory path?

   Please try this for get the url of root file.

First Way:

 $path = get_home_path();
   print "Path: ".$path; 
// Return "Path: /var/www/htdocs/" or

// "Path: /var/www/htdocs/wordpress/" if it is subfolder

Second Way:

And you can also use 

    "ABSPATH"

this constant is define in wordpress config file.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..

Happy Coding :)

Why Response.Redirect causes System.Threading.ThreadAbortException?

This is just how Response.Redirect(url, true) works. It throws the ThreadAbortException to abort the thread. Just ignore that exception. (I presume it is some global error handler/logger where you see it?)

An interesting related discussion Is Response.End() Considered Harmful?.

How to clear cache in Yarn?

Ok I found out the answer myself. Much like npm cache clean, Yarn also has its own

yarn cache clean

How to encode URL parameters?

With PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

Result

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

With Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

DEMO: http://jsfiddle.net/Lpv53/

Why is AJAX returning HTTP status code 0?

In my troubleshooting, I found this AJAX xmlhttpRequest.status == 0 could mean the client call had NOT reached the server yet, but failed due to issue on the client side. If the response was from server, then the status must be either those 1xx/2xx/3xx/4xx/5xx HTTP Response code. Henceforth, the troubleshooting shall focus on the CLIENT issue, and could be internet network connection down or one of those described by @Langdon above.

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>