Programs & Examples On #Expression blend 3

macOS on VMware doesn't recognize iOS device

Do what is suggested in the answer, but make sure you also click inside the VM so that OSX has the focus before you plug in the phone. In my case, I had to do that to make it work.

laravel select where and where condition

Here is shortest way of doing it.

$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();

Execute a PHP script from another PHP script

you can use the backtick notation:

`php file.php`;

You can also put this at the top of the php file to indicate the interpreter:

#!/usr/bin/php

Change it to where you put php. Then give execute permission on the file and you can call the file without specifying php:

`./file.php`

If you want to capture the output of the script:

$output = `./file.php`;
echo $output;

CSS3 Transition - Fade out effect

Since display is not one of the animatable CSS properties. One display:none fadeOut animation replacement with pure CSS3 animations, just set width:0 and height:0 at last frame, and use animation-fill-mode: forwards to keep width:0 and height:0 properties.

@-webkit-keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}  
@keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}

.display-none.on{
    display: block;
    -webkit-animation: fadeOut 1s;
    animation: fadeOut 1s;
    animation-fill-mode: forwards;
}

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Netbeans Problem: For apache Tomcat server Authentication required dialog box requesting user name and password

This dialog box appear If a user role and his credentials are not set or is incorrect for Tomcat startup via NetBeans IDE,

OR when user/pass set in IDE is not matches with user/pass in "canf/tomcat-user.xml" file

1..Need to check user name and password set in IDE tools-->server

2..Check \CATALINA_BASE\conf\tomcat-users.xml. whether user and his role is defined or not. If not add these lines

<user username="ide" password="EiWnNlBG" roles="manager-script,admin"/>
</tomcat-users>

3.. set the same user/pass in IDE tools->server

  1. restart your server to get effect of changes

Source: http://ohmjavaclasses.blogspot.com/2011/12/netbeans-problem-for-apache-tomcat.html

Pure Javascript listen to input value change

instead of id use title to identify your element and write the code as below.

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Removing object from array in Swift 3

In Swift 3 and 4

var array = ["a", "b", "c", "d", "e", "f"]

for (index, element) in array.enumerated().reversed() {
    array.remove(at: index)
}

From Swift 4.2 you can use more advanced approach(faster and memory efficient)

array.removeAll(where: { $0 == "c" })

instead of

array = array.filter { !$0.hasPrefix("c") }

Read more here

Swapping two variable value without using third variable

R is missing a concurrent assignment as proposed by Edsger W. Dijkstra in A Discipline of Programming, 1976, ch.4, p.29. This would allow for an elegant solution:

a, b    <- b, a         # swap
a, b, c <- c, a, b      # rotate right

Detect page change on DataTable

$('#tableId').on('draw.dt', function() {
    //This will get called when data table data gets redrawn to the      table.
});

How to change the icon of an Android app in Eclipse?

You can find an easy guide here

The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

How to install pip for Python 3.6 on Ubuntu 16.10?

This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.

http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/

A short summary:

sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2

Then

$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

Then to select python 3.6 run

sudo update-alternatives --config python3

and select '2'. Then

$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

To update pip select the desired version and

pip3 install --upgrade pip

$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Tested on Ubuntu 16.04.

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Thay are removed.

Use float-left instead of pull-left. And float-right instead of pull-right.

Check bootstrap Documentation here:

Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.

Import text file as single character string

It seems your solution is not much ugly. You can use functions and make it proffesional like these ways

  • first way
new.function <- function(filename){
  readChar(filename, file.info(filename)$size)
}

new.function('foo.txt')
  • second way
new.function <- function(){
  filename <- 'foo.txt'
  return (readChar(filename, file.info(filename)$size))
}

new.function()

Get the latest date from grouped MySQL data

And why not to use this ?

SELECT model, date FROM doc ORDER BY date DESC LIMIT 1

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

What is the facade design pattern?

Regarding your queries:

Is Facade a class which contains a lot of other classes?

Yes. It is a wrapper for many sub-systems in application.

What makes it a design pattern? For me, it is like a normal class

All design patterns too are normal classes. @Unmesh Kondolikar rightly answered this query.

Can you explain me about this Facade, I am new to design patterns.

According to GoF, Facade design pattern is defind as :

Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use

The Facade pattern is typically used when:

  1. A simple interface is required to access a complex system.
  2. The abstractions and implementations of a subsystem are tightly coupled.
  3. Need an entry point to each level of layered software.
  4. System is very complex or difficult to understand.

Let's take a real word example of cleartrip website.

This website provides options to book

  1. Flights
  2. Hotels
  3. Flights + Hotels

Code snippet:

import java.util.*;

public class TravelFacade{
    FlightBooking flightBooking;
    TrainBooking trainBooking;
    HotelBooking hotelBooking;

    enum BookingType {
        Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
    }; 

    public TravelFacade(){
        flightBooking = new FlightBooking();
        trainBooking = new TrainBooking();
        hotelBooking = new HotelBooking();        
    }
    public void book(BookingType type, BookingInfo info){
        switch(type){
            case Flight:
                // book flight;
                flightBooking.bookFlight(info);
                return;
            case Hotel:
                // book hotel;
                hotelBooking.bookHotel(info);
                return;
            case Train:
                // book Train;
                trainBooking.bookTrain(info);
                return;
            case Flight_And_Hotel:
                // book Flight and Hotel
                flightBooking.bookFlight(info);
                hotelBooking.bookHotel(info);
                return;
             case Train_And_Hotel:
                // book Train and Hotel
                trainBooking.bookTrain(info);
                hotelBooking.bookHotel(info);
                return;                
        }
    }
}
class BookingInfo{
    String source;
    String destination;
    Date    fromDate;
    Date     toDate;
    List<PersonInfo> list;
}
class PersonInfo{
    String name;
    int       age;
    Address address;
}
class Address{

}
class FlightBooking{
    public FlightBooking(){

    }
    public void bookFlight(BookingInfo info){

    }
}
class HotelBooking{
    public HotelBooking(){

    }
    public void bookHotel(BookingInfo info){

    }
}
class TrainBooking{
    public TrainBooking(){

    }
    public void bookTrain(BookingInfo info){

    }
}

Explanation:

  1. FlightBooking, TrainBooking and HotelBooking are different sub-systems of large system : TravelFacade

  2. TravelFacade offers a simple interface to book one of below options

    Flight Booking
    Train Booking 
    Hotel Booking
    Flight + Hotel booking 
    Train + Hotel booking
    
  3. book API from TravelFacade internally calls below APIs of sub-systems

    flightBooking.bookFlight
    trainBooking.bookTrain(info);
    hotelBooking.bookHotel(info);
    
  4. In this way, TravelFacade provides simpler and easier API with-out exposing sub-system APIs.

Key takeaways : ( from journaldev article by Pankaj Kumar)

  1. Facade pattern is more like a helper for client applications
  2. Facade pattern can be applied at any point of development, usually when the number of interfaces grow and system gets complex.
  3. Subsystem interfaces are not aware of Facade and they shouldn’t have any reference of the Facade interface
  4. Facade pattern should be applied for similar kind of interfaces, its purpose is to provide a single interface rather than multiple interfaces that does the similar kind of jobs

Have a look at sourcemaking article too for better understanding.

Java - Opposite of .contains (does not contain)

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

How to get parameters from a URL string?

$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- see the value

This is working great for me using php

How to generate a HTML page dynamically using PHP?

I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you

What is the syntax for adding an element to a scala.collection.mutable.Map?

Create a mutable map without initial value:

scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = Map()

Create a mutable map with initial values:

scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test")
d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234)

Update existing key-value:

scala> d("a")= "ABC"

Add new key-value:

scala> d(100)= "new element"

Check the updated map:

scala> d
res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)

Dropdown select with images

Seems like a straightforward html menu would be simpler. Use html5 data attributes for values or whatever method you want to store them and css to handle images as backgrounds or put them in the html itself.

Edit: If you are forced to convert from an existing select that you can't get rid of, there are some good plugins as well to modify a select to html. Wijmo and Chosen are a couple that come to mind

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

Running EXE with parameters

ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false; 
System.Diagnostics.Process.Start(startInfo);

node.js require all files in a folder?

If you include all files of *.js in directory example ("app/lib/*.js"):

In directory app/lib

example.js:

module.exports = function (example) { }

example-2.js:

module.exports = function (example2) { }

In directory app create index.js

index.js:

module.exports = require('./app/lib');

String.Replace ignoring case

Doesn't this work: I cant imaging anything else being much quicker or easier.

public static class ExtensionMethodsString
{
    public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
    {
        string working = thisString;
        int index = working.IndexOf(oldValue, stringComparison);
        while (index != -1)
        {
            working = working.Remove(index, oldValue.Length);
            working = working.Insert(index, newValue);
            index = index + newValue.Length;
            index = working.IndexOf(oldValue, index, stringComparison);
        }
        return working;
    }
}

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

How to convert a string Date to long millseconds

Try below code

        SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
        Date d = null;
        try {
            d = f.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timeInMillis = d.getTime();

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

Is it possible to use Java 8 for Android development?

Follow this link for new updates. Use Java 8 language features

Old Answer

As of Android N preview release Android support limited features of Java 8 see Java 8 Language Features

To start using these features, you need to download and set up Android Studio 2.1 and the Android N Preview SDK, which includes the required Jack toolchain and updated Android Plugin for Gradle. If you haven't yet installed the Android N Preview SDK, see Set Up to Develop for Android N.

Supported Java 8 Language Features and APIs

Android does not currently support all Java 8 language features. However, the following features are now available when developing apps targeting the Android N Preview:

Default and static interface methods

Lambda expressions (also available on API level 23 and lower)

Repeatable annotations

Method References (also available on API level 23 and lower)

There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features

Update

Note: The Android N bases its implementation of lambda expressions on anonymous classes. This approach allows them to be backwards compatible and executable on earlier versions of Android. To test lambda expressions on earlier versions, remember to go to your build.gradle file, and set compileSdkVersion and targetSdkVersion to 23 or lower.

Update 2

Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features (without the Jack compiler).

How do I save and restore multiple variables in python?

There is a built-in library called pickle. Using pickle you can dump objects to a file and load them later.

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

Remove Server Response Header IIS7

With the URL Rewrite Module Version 2.0 for IIS (UrlRewrite) enabled, in the configuration section <configuration> ? <system.webServer> ? <rewrite> add the outbound rule:

<outboundRules>
  <rule name="Remove RESPONSE_Server" >
    <match serverVariable="RESPONSE_Server" pattern=".+" />
    <action type="Rewrite" value="" />
  </rule>
</outboundRules>

When saving, how can you check if a field has changed?

As of Django 1.8, there's the from_db method, as Serge mentions. In fact, the Django docs include this specific use case as an example:

https://docs.djangoproject.com/en/dev/ref/models/instances/#customizing-model-loading

Below is an example showing how to record the initial values of fields that are loaded from the database

How to downgrade tensorflow, multiple versions possible?

Pip allows to specify the version

pip install tensorflow==1.1

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

sum two columns in R

It could be that one or two of your columns may have a factor in them, or what is more likely is that your columns may be formatted as factors. Please would you give str(col1) and str(col2) a try? That should tell you what format those columns are in.

I am unsure if you're trying to add the rows of a column to produce a new column or simply all of the numbers in both columns to get a single number.

A KeyValuePair in Java

Hashtable<String, Object>

It is better than java.util.Properties which is by fact an extension of Hashtable<Object, Object>.

How do I "commit" changes in a git submodule?

$ git submodule status --recursive

Is also a life saver in this situation. You can use it and gitk --all to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

After testing on Juno, Kepler and Luna, I found JD only works for *.class files on build path.

  1. Adding the jar as a lib of an existing project
  2. Go to Preferences->General->Editors->File Associations, set *.class without source to Class File Editor with a cup icon

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Is a LINQ statement faster than a 'foreach' loop?

It should probably be noted that the for loop is faster than the foreach. So for the original post, if you are worried about performance on a critical component like a renderer, use a for loop.

Reference: In .NET, which loop runs faster, 'for' or 'foreach'?

CSS Background image not loading

the following code worked for me where i had placed the image in somefolder/assets/img/background_some_img.jpg

background-image: url('../img/background_some_img.jpg');
background-size: cover;
background-repeat: no-repeat;

Git on Mac OS X v10.7 (Lion)

You have to find where the Git executable is and then add the folder to the PATH environment variable in file .bash_profile.

Using terminal:

  1. Search for Git:

     sudo find / -name git
    
  2. Edit the .bash_profile file. Add:

     PATH="<Directory of Git>:$PATH"
    

Git is back :-)

Anyway, I suggest you to install Git using MacPorts. In this way you can easily upgrade your Git instance to the newest release.

Ignoring NaNs with str.contains

I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.

import pandas as pd
import numpy as np

df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

newdf = df.loc[df['a'].str.contains('foo') == True]

Works with or without .loc.

I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True or False. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.

How do I export a project in the Android studio?

Follow the below steps to sign the application in the android studio:-

  1. First Go to Build->Generate Signed APK

    First screenshot

  2. Then Once you click on the Generate Signed APK then there is info dialog message appear.

    Second screenshot

  3. Click on the Create New button if you don't have any keystore file. If you have click on the Choose Existing.

    This screenshot

  4. Once you click on the Create New button then now dialog box appear where you need to enter the keystore file info, other signing authority details.

    Fourth screenshot

  5. Once you fill complete details then click on the Ok button then it redirect to this dialog.

    Fifth screenshot

  6. Click on the Next button then check mark on the Run ProGuard and click on the finish. It generate the signed APK.

    Sixth screenshot

    Seventh screenshot

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

How do I turn off PHP Notices?

You can check if the constant's already defined using:

<?php
if (!defined('MYCONST'))
    define('MYCONST', 'Weeha!');
?>

How to use phpexcel to read data and insert into database?

      if($query)
       {
        // try to export to excel the whole data ---
        //initialize php excel first  
        ob_end_clean();
        //--- create php excel object ---
        $objPHPExcel = new PHPExcel();
        //define cachemethod
        ini_set('memory_limit', '3500M');
        $cacheMethod   = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize' => '800MB');
        //set php excel settings
        PHPExcel_Settings::setCacheStorageMethod(
                $cacheMethod,$cacheSettings
              );


        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");

        $objPHPExcel->setActiveSheetIndex(0);

        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }

        // Fetching the table data
        $row = 2;
        foreach($query->result() as $data)
        {
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }

            $row++;
        }

        $objPHPExcel->setActiveSheetIndex(0);
        //redirect to cleint browser
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=Provinces.xlsx');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
     }

How to pass anonymous types as parameters?

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

Checking if date is weekend PHP

Here:

function isweekend($year, $month, $day)
{
    $time = mktime(0, 0, 0, $month, $day, $year);
    $weekday = date('w', $time);
    return ($weekday == 0 || $weekday == 6);
}

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

How do I access ViewBag from JS

<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

How to open google chrome from terminal?

just type

google-chrome

it works. Thanks.

Android Studio: Module won't show up in "Edit Configuration"

None of the previous answers worked for me, so I deleted and reinstalled Android Studio. Worked like a charm.

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

How do I make entire div a link?

You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

<a style="display:block" href="http://justinbieber.com">
  <div class="xyz">My div contents</div>
</a>

Can I stop 100% Width Text Boxes from extending beyond their containers?

Actually, it's because CSS defines 100% relative to the entire width of the container, including its margins, borders, and padding; that means that the space avail. to its contents is some amount smaller than 100%, unless the container has no margins, borders, or padding.

This is counter-intuitive and widely regarded by many to be a mistake that we are now stuck with. It effectively means that % dimensions are no good for anything other than a top level container, and even then, only if it has no margins, borders or padding.

Note that the text field's margins, borders, and padding are included in the CSS size specified for it - it's the container's which throw things off.

I have tolerably worked around it by using 98%, but that is a less than perfect solution, since the input fields tend to fall further short as the container gets larger.


EDIT: I came across this similar question - I've never tried the answer given, and I don't know for sure if it applies to your problem, but it seems like it will.

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

jquery datatables default sort

Here is the actual code that does it...

$(document).ready(function()
{
  var oTable = $('#myTable').dataTable();

  // Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
  oTable.fnSort( [ [1,'asc'] ] );

  // And to sort another column descending (at position 2 in the array (base 0).
  oTable.fnSort( [ [2,'desc'] ] );
} );

To not have the column highlighted, modify the CSS like so:

table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }

SVN: Folder already under version control but not comitting?

A variation on @gauss256's answer, deleting .svn, worked for me:

rm -rf troublesome_folder/.svn
svn add troublesome_folder
svn commit

Before Gauss's solution I tried @jwir3's approach and got no joy:

svn cleanup
svn cleanup *
svn cleanup troublesome_folder
svn add --force troublesome_folder
svn commit

Simple and clean way to convert JSON string to Object in Swift

Here are some tips how to begin with simple example.

Consider you have following JSON Array String (similar to yours) like:

 var list:Array<Business> = []

  // left only 2 fields for demo
  struct Business {
    var id : Int = 0
    var name = ""               
 }

 var jsonStringAsArray = "[\n" +
        "{\n" +
        "\"id\":72,\n" +
        "\"name\":\"Batata Cremosa\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":183,\n" +
        "\"name\":\"Caldeirada de Peixes\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":76,\n" +
        "\"name\":\"Batata com Cebola e Ervas\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":56,\n" +
        "\"name\":\"Arroz de forma\",\n" +            
    "}]"


        // convert String to NSData
        var data: NSData = jsonStringAsArray.dataUsingEncoding(NSUTF8StringEncoding)!
        var error: NSError?

        // convert NSData to 'AnyObject'
        let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),
            error: &error)
        println("Error: \(error)")

     // convert 'AnyObject' to Array<Business>
     list = self.parseJson(anyObj!)

     //===============

    func parseJson(anyObj:AnyObject) -> Array<Business>{

        var list:Array<Business> = []

         if  anyObj is Array<AnyObject> {

            var b:Business = Business()

            for json in anyObj as Array<AnyObject>{
             b.name = (json["name"] as AnyObject? as? String) ?? "" // to get rid of null
             b.id  =  (json["id"]  as AnyObject? as? Int) ?? 0                 

               list.append(b)
            }// for

        } // if

      return list

    }//func    

[EDIT]

To get rid of null changed to:

b.name = (json["name"] as AnyObject? as? String) ?? ""
b.id  =  (json["id"]  as AnyObject? as? Int) ?? 0 

See also Reference of Coalescing Operator (aka ??)

Hope it will help you to sort things out,

raw vs. html_safe vs. h to unescape html

In Simple Rails terms:

h remove html tags into number characters so that rendering won't break your html

html_safe sets a boolean in string so that the string is considered as html save

raw It converts to html_safe to string

Add/Delete table rows dynamically using JavaScript

Here Is full code with HTML,CSS and JS.

<style><style id='generate-style-inline-css' type='text/css'>
    body {
        background-color: #efefef;
        color: #3a3a3a;
    }

    a,
    a:visited {
        color: #1e73be;
    }

    a:hover,
    a:focus,
    a:active {
        color: #000000;
    }

    body .grid-container {
        max-width: 1200px;
    }

    body,
    button,
    input,
    select,
    textarea {
        font-family: "Open Sans", sans-serif;
    }

    .entry-content>[class*="wp-block-"]:not(:last-child) {
        margin-bottom: 1.5em;
    }

    .main-navigation .main-nav ul ul li a {
        font-size: 14px;
    }

    @media (max-width:768px) {
        .main-title {
            font-size: 30px;
        }
        h1 {
            font-size: 30px;
        }
        h2 {
            font-size: 25px;
        }
    }

    .top-bar {
        background-color: #636363;
        color: #ffffff;
    }

    .top-bar a,
    .top-bar a:visited {
        color: #ffffff;
    }

    .top-bar a:hover {
        color: #303030;
    }

    .site-header {
        background-color: #ffffff;
        color: #3a3a3a;
    }

    .site-header a,
    .site-header a:visited {
        color: #3a3a3a;
    }

    .main-title a,
    .main-title a:hover,
    .main-title a:visited {
        color: #222222;
    }

    .site-description {
        color: #757575;
    }

    .main-navigation,
    .main-navigation ul ul {
        background-color: #222222;
    }

    .main-navigation .main-nav ul li a,
    .menu-toggle {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li:hover>a,
    .main-navigation .main-nav ul li:focus>a,
    .main-navigation .main-nav ul li.sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    button.menu-toggle:hover,
    button.menu-toggle:focus,
    .main-navigation .mobile-bar-items a,
    .main-navigation .mobile-bar-items a:hover,
    .main-navigation .mobile-bar-items a:focus {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"],
    .navigation-search input[type="search"]:active {
        color: #3f3f3f;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"]:focus {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation ul ul {
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul ul li a {
        color: #ffffff;
    }

    .main-navigation .main-nav ul ul li:hover>a,
    .main-navigation .main-nav ul ul li:focus>a,
    .main-navigation .main-nav ul ul li.sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation . main-nav ul ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .separate-containers .inside-article,
    .separate-containers .comments-area,
    .separate-containers .page-header,
    .one-container .container,
    .separate-containers .paging-navigation,
    .inside-page-header {
        background-color: #ffffff;
    }

    .entry-meta {
        color: #595959;
    }

    .entry-meta a,
    .entry-meta a:visited {
        color: #595959;
    }

    .entry-meta a:hover {
        color: #1e73be;
    }

    .sidebar .widget {
        background-color: #ffffff;
    }

    .sidebar .widget .widget-title {
        color: #000000;
    }

    .footer-widgets {
        background-color: #ffffff;
    }

    .footer-widgets .widget-title {
        color: #000000;
    }

    .site-info {
        color: #ffffff;
        background-color: #222222;
    }

    .site-info a,
    .site-info a:visited {
        color: #ffffff;
    }

    .site-info a:hover {
        color: #606060;
    }

    .footer-bar .widget_nav_menu .current-menu-item a {
        color: #606060;
    }

    input[type="text"],
    input[type="email"],
    input[type="url"],
    input[type="password"],
    input[type="search"],
    input[type="tel"],
    input[type="number"],
    textarea,
    select {
        color: #666666;
        background-color: #fafafa;
        border-color: #cccccc;
    }

    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="url"]:focus,
    input[type="password"]:focus,
    input[type="search"]:focus,
    input[type="tel"]:focus,
    input[type="number"]:focus,
    textarea:focus,
    select:focus {
        color: #666666;
        background-color: #ffffff;
        border-color: #bfbfbf;
    }

    button,
    html input[type="button"],
    input[type="reset"],
    input[type="submit"],
    a.button,
    a.button:visited,
    a.wp-block-button__link:not(.has-background) {
        color: #ffffff;
        background-color: #666666;
    }

    button:hover,
    html input[type="button"]:hover,
    input[type="reset"]:hover,
    input[type="submit"]:hover,
    a.button:hover,
    button:focus,
    html input[type="button"]:focus,
    input[type="reset"]:focus,
    input[type="submit"]:focus,
    a.button:focus,
    a.wp-block-button__link:not(.has-background):active,
    a.wp-block-button__link:not(.has-background):focus,
    a.wp-block-button__link:not(.has-background):hover {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .generate-back-to-top,
    .generate-back-to-top:visited {
        background-color: rgba( 0, 0, 0, 0.4);
        color: #ffffff;
    }

    .generate-back-to-top:hover,
    .generate-back-to-top:focus {
        background-color: rgba( 0, 0, 0, 0.6);
        color: #ffffff;
    }

    .entry-content .alignwide,
    body:not(.no-sidebar) .entry-content .alignfull {
        margin-left: -40px;
        width: calc(100% + 80px);
        max-width: calc(100% + 80px);
    }

    @media (max-width:768px) {
        .separate-containers .inside-article,
        .separate-containers .comments-area,
        .separate-containers .page-header,
        .separate-containers .paging-navigation,
        .one-container .site-content,
        .inside-page-header {
            padding: 30px;
        }
        .entry-content .alignwide,
        body:not(.no-sidebar) .entry-content .alignfull {
            margin-left: -30px;
            width: calc(100% + 60px);
            max-width: calc(100% + 60px);
        }
    }

    .rtl .menu-item-has-children .dropdown-menu-toggle {
        padding-left: 20px;
    }

    .rtl .main-navigation .main-nav ul li.menu-item-has-children>a {
        padding-right: 20px;
    }

    .one-container .sidebar .widget {
        padding: 0px;
    }

    .append_row {
        color: black !important;
        background-color: #FFD6D6 !important;
        border: 1px #ccc solid !important;
    }

    .append_column {
        color: black !important;
        background-color: #D6FFD6 !important;
        border: 1px #ccc solid !important;
    }

    table#my-table td {
        width: 50px;
        height: 27px;
        border: 1px solid #D3D3D3;
        text-align: center;
        padding: 0;
    }

    div#my-container input {
        padding: 5px;
        font-size: 12px !important;
        width: 100px;
        margin: 2px;
    }

    .row {
        background-color: #FFD6D6 !important;
    }

    .col {
        background-color: #D6FFD6 !important;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.11.0.js"></script>
    <script>

    // append row to the HTML table
    function appendRow() {
        var tbl = document.getElementById('my-table'), // table reference
            row = tbl.insertRow(tbl.rows.length),      // append table row
            i;
        // insert table cells to the new row
        for (i = 0; i < tbl.rows[0].cells.length; i++) {
            createCell(row.insertCell(i), i, 'row');
        }
    }

    // create DIV element and append to the table cell
    function createCell(cell, text, style) {
        var div = document.createElement('div'), // create DIV element
            txt = document.createTextNode(text); // create text node
        div.appendChild(txt);                    // append text node to the DIV
        div.setAttribute('class', style);        // set DIV class attribute
        div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
        cell.appendChild(div);                   // append DIV to the table cell
    }

    // append column to the HTML table
    function appendColumn() {
        var tbl = document.getElementById('my-table'), // table reference
            i;
        // open loop for each row and append cell
        for (i = 0; i < tbl.rows.length; i++) {
            createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
        }
    }

    // delete table rows with index greater then 0
    function deleteRows() {
        var tbl = document.getElementById('my-table'), // table reference
            lastRow = tbl.rows.length - 1,             // set the last row index
            i;
        // delete rows with index greater then 0
        for (i = lastRow; i > 0; i--) {
            tbl.deleteRow(i);
        }
    }

    // delete table columns with index greater then 0
    function deleteColumns() {
        var tbl = document.getElementById('my-table'), // table reference
            lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
            i, j;
        // delete cells with index greater then 0 (for each row)
        for (i = 0; i < tbl.rows.length; i++) {
            for (j = lastCol; j > 0; j--) {
                tbl.rows[i].deleteCell(j);
            }
        }
    }
    </script>
    <div id="my-container">
    <center><br>
    <input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"><br>
    <input type="button" value="Add column" onclick="javascript:appendColumn()" class="append_column"><br>
    <input type="button" value="Delete rows" onclick="javascript:deleteRows()" class="delete"><br>
    <input type="button" value="Delete columns" onclick="javascript:deleteColumns()" class="delete"><br>
    <input type="button" value="Delete both" onclick="javascript:deleteColumns();deleteRows()" class="delete"><p></p>
    <table id="my-table" align="center" cellspacing="0" cellpadding="0" border="0">
    <tbody><tr>
    <td>Small</td>
    </tr>
    </tbody></table>
    <p></p></center>
    </div>

How to get the response of XMLHttpRequest?

In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

 Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
 The value is only accessible if the object\'s \'responseType\' is \'\' 
 or \'text\' (was \'arraybuffer\')

Best way to access the response from XHR as follows

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);

Rounded Corners Image in Flutter

You can use CircleAvatar Widget with radius:

CircleAvatar(
             radius: 50.0,
             backgroundImage: AssetImage("assets/img1.jpeg"),
            ),

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Try changing the port number in your project?

Project Properties ? Web ? Servers ? Project Url:

enter image description here

Don't forget to click Create Virtual Directory, or reply "Yes" to the prompt for creating virtual directory after you change your port number! (Thanks Connor)

Note: I'm a little reluctant to post this as an answer, as I have no idea what the issue is or what caused it, but I had a similar issue, and changing the port number did the trick for me. I'm only posting this per the suggestion in the comments that this worked for someone else as well.

In my case, it seemed like something was conflicting with the specific port number I was using, so I changed to a different one, and my site popped right back up! I'm not sure what that means for the old port number, or if I'll ever be able to use it again. Maybe someone more knowledgeable than myself can chime in on this.

Service has zero application (non-infrastructure) endpoints

As another clue, that indeed fixed this issue in my case.

I'm migrating some WCF services from a console application (that configures in code few WCF services) to an Azure WebRole to publish them in Azure. Every time I add a new service VS edits my web.config and adds this line:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">

Well, with all the advices and answers above I couldn't make it work until I removed all the attributes in the serviceHostingEnvironment element. As you can see I'm not a WCF rockstar but I made it to work with the first Service just by configuring it as:

<service name="FirstService" behaviorConfiguration="metadataBehavior">
                <endpoint address=""
                 binding="wsHttpBinding"
                 bindingConfiguration="WSHttpBinding_WcfServicesBinding"
                 contract="IFirstService" />

            </service>

but when I added the second Service it stoped working and I realized that those attributes where there again.

I hope it saves you time.

Get GPS location from the web browser

Observable

/*
  function geo_success(position) {
    do_something(position.coords.latitude, position.coords.longitude);
  }

  function geo_error() {
    alert("Sorry, no position available.");
  }

  var geo_options = {
    enableHighAccuracy: true,
    maximumAge        : 30000,
    timeout           : 27000
  };

  var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
  */
  getLocation(): Observable<Position> {
    return Observable.create((observer) => {
      const watchID = navigator.geolocation.watchPosition((position: Position) => {
        observer.next(position);
      });
      return () => {
        navigator.geolocation.clearWatch(watchID);
      };
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

JavaScript OOP in NodeJS: how?

This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.

Well in a file animal.js you would write:

var method = Animal.prototype;

function Animal(age) {
    this._age = age;
}

method.getAge = function() {
    return this._age;
};

module.exports = Animal;

To use it in other file:

var Animal = require("./animal.js");

var john = new Animal(3);

If you want a "sub class" then inside mouse.js:

var _super = require("./animal.js").prototype,
    method = Mouse.prototype = Object.create( _super );

method.constructor = Mouse;

function Mouse() {
    _super.constructor.apply( this, arguments );
}
//Pointless override to show super calls
//note that for performance (e.g. inlining the below is impossible)
//you should do
//method.$getAge = _super.getAge;
//and then use this.$getAge() instead of super()
method.getAge = function() {
    return _super.getAge.call(this);
};

module.exports = Mouse;

Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:

 var method = List.prototype;
 function List() {

 }

 method.add = Array.prototype.push;

 ...

 var a = new List();
 a.add(3);
 console.log(a[0]) //3;

unknown type name 'uint8_t', MinGW

I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.

I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Simple Steps

  1. 1 Open SQL Server Configuration Manager
  2. Under SQL Server Services Select Your Server
  3. Right Click and Select Properties
  4. Log on Tab Change Built-in-account tick
  5. in the drop down list select Network Service
  6. Apply and start The service

How to execute a Windows command on a remote PC?

psexec \\RemoteComputer cmd.exe

or use ssh or TeamViewer or RemoteDesktop!

C++ performance vs. Java/C#

Here's an interesting benchmark http://zi.fi/shootout/

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

Concatenating Files And Insert New Line In Between Files

If it were me doing it I'd use sed:

sed -e '$s/$/\n/' -s *.txt > finalfile.txt

In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.

If your version of sed doesn't have -s (process input files separately) you can do it all as a loop though:

for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

HTTP Error 500.30 - ANCM In-Process Start Failure

I looked at the Windows Logs under Application. It displayed the error message and stack trace. I found out I was missing a folder called node_modules. I created that folder and that fixed it.

I did not make any changes to web.config or the project file. My .NETCoreApp version was 3.1

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Error inflating class android.support.v7.widget.Toolbar?

I was able to solve this problem by replacing the following:

In the Toolbar layout, replace everything which is like this:

android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"

with

android:minHeight="@dimen/abc_action_bar_default_height_material"
android:background="@color/myColor"

How to scanf only integer and repeat reading if the user enters non-numeric characters?

#include <stdio.h>
main()
{
    char str[100];
    int num;
    while(1) {
        printf("Enter a number: ");
        scanf("%[^0-9]%d",str,&num);
        printf("You entered the number %d\n",num);
    }
    return 0;
}

%[^0-9] in scanf() gobbles up all that is not between 0 and 9. Basically it cleans the input stream of non-digits and puts it in str. Well, the length of non-digit sequence is limited to 100. The following %d selects only integers in the input stream and places it in num.

Color Tint UIButton Image

To set white colour of the image(arrow icon) on the button, we're using:

let imageOnButton = UIImage(named: "navForwardArrow")?.imageWithColor(color: UIColor.white)
button.setImage(imageOnButton, for: .normal)

Known issue: The icon looses its white colour while the button is pressed.

Screenshot: enter image description here

Where do alpha testers download Google Play Android apps?

Google play store provides closed testing track to test your application with a limited set of testers pre-defined in the tester's list known as Alpha Testing. Here are some important things to be considered to use alpha testing.

Important

After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers

Managing Testers for Alpha Testing

Manage Testers

  1. The Screenshot is most recent as of answering this question. You can see the manage testers for closed alpha testing, You can add and remove tester one by one or you can use CSV file to bulk add and remove. The list of defined email addresses will be eligible for testing the app, here you can a control whom to provide the app for testing. Hence, this is known as Closed Testing.
  2. You can see the link(washed out by red line), once your app available to test, your testers can download and test the app by going to the below-given link. For that Google will ask once to the tester for joining the testing program. Once they have joined the program, they will receive an app update. As stated by store, it may take 24 hours to make an app available for testing.
  3. Once your app available, Your invited testers can join the test by going the link https://play.google.com/apps/testing/YOUR PACKAGE NAME

Managing App Releases

Manage Release for Alpha

  1. After the Manage testers card, there is a card for manage release, from here you can manage your alpha releases and roll-out them to production by clicking the button at the top of the card once they well tested. This process of rolling out from testing to production/public is known as stagged roll-out. In stagged roll-out, the publisher publishes by the percentage of users, to better analyze the user response.
  2. You can also manage multiple alpha release app versions from here, at the bottom of the screenshot you can see that I have once more apk build version being served as alpha test app.

Managing Closed Track Testing Availability

Alpha Country Availibility

  1. Apart from the user based control, you have one more control over the availability of the app for a test in the country. You can add limited countries tester to the app. suppose your list of the testers are from multiple countries and you want the application to be tested in your country only, rather removing testers from the testing list, you can go through Alpha Country Availability. It gives more precise control over testers.
  2. Here, In Screenshot, my app is available worldwide states that my testers (from testers list) can test the app in all countries.

In what cases will HTTP_REFERER be empty

It will also be empty if the new Referrer Policy standard draft is used to prevent that the referer header is sent to the request origin. Example:

<meta name="referrer" content="none">

Although Chrome and Firefox have already implemented a draft version of the Referrer Policy, you should be careful with it because for example Chrome expects no-referrer instead of none (and I have seen also never somewhere).

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

you seem to have not created an main method, which should probably look something like this (i am not sure)

  class RunThis
{
    public static void main(String[] args)
    {

    Calculate answer = new Calculate();
    answer.getNumber1();
    answer.getNumber2();
    answer.setNumber(answer.getNumber1() , answer.getNumber2());
    answer.getOper();
    answer.setOper(answer.getOper());
    answer.getAnswer();
    }
}

the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.

I am new to java this may or may not be the right answer, correct me if i am wrong

How do I convert datetime to ISO 8601 in PHP

How to convert from ISO 8601 to unixtimestamp :

strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500

How to convert from unixtimestamp to ISO 8601 (timezone server) :

date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00

How to convert from unixtimestamp to ISO 8601 (GMT) :

date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00

How to convert from unixtimestamp to ISO 8601 (custom timezone) :

date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00

How to set OnClickListener on a RadioButton in Android?

For Kotlin Here is added the lambda expression and Optimized the Code.

   radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
        run {
            when (optionId) {
                R.id.radioButton1 -> {
                    // do something when radio button 1 is selected
                }
                R.id.radioButton2 -> {
                    // do something when radio button 2 is selected
                }
                // add more cases here to handle other buttons in the your RadioGroup
            }
        }
    }

Hope this will help you. Thanks!

error: RPC failed; curl transfer closed with outstanding read data remaining

When I tried cloning from the remote, got the same issue repeatedly:

remote: Counting objects: 182, done.
remote: Compressing objects: 100% (149/149), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

Finally this worked for me:

git clone https://[email protected]/repositoryName.git --depth 1

How do you run a single test/spec file in RSpec?

To run all of your rspec files: rspec

note: you must be in the root of your project

To run one rspec file: rspec 'path_to/spec.rb'

note: replace 'path_to/spec.rb' with your path. Quotation marks optional.

To run one rspec test from one file: rspec 'path_to/spec.rb:7'

note: :7 is the line number where the test starts

Gson - convert from Json to a typed ArrayList<T>

Your JSON sample is:

{
    "status": "ok",
    "comment": "",
    "result": {
    "id": 276,
    "firstName": "mohamed",
    "lastName": "hussien",
    "players": [
            "player 1",
            "player 2",
            "player 3",
            "player 4",
            "player 5"
    ]
}

so if you want to save arraylist of modules in your SharedPrefrences so :

1- will convert your returned arraylist for json format using this method

public static String toJson(Object jsonObject) {
    return new Gson().toJson(jsonObject);
}

2- Save it in shared prefreneces

PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));

3- to retrieve it at any time get JsonString from Shared preferences like that

String playersString= PreferencesUtils.getInstance(this).getString("players");

4- convert it again to array list

public static Object fromJson(String jsonString, Type type) {
    return new Gson().fromJson(jsonString, type);
}

ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString,
                    new TypeToken<ArrayList<String>>() {
                    }.getType());

this solution also doable if you want to parse ArrayList of Objects Hope it's help you by using Gson Library .

R: Print list to a text file

Here's another way using sink:

sink(sink_dir_and_file_name); print(yourList); sink()

Java: how to represent graphs?

Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.

public class Edge {
    private Node a, b;
    private directionEnum direction;     // AB, BA or both
    private int weight;
    ...
}

It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/

How to style the UL list to a single line

HTML code:

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

CSS code:

ul.list li{
  width: auto;
  float: left;
}

Twitter Bootstrap Multilevel Dropdown Menu

I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:

.dropdown-menu li {
    position: relative;
}

I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).

Here is the full less/css change (replace the above with this):

.dropdown-menu li {
    position: relative;

    [class^="icon-"] {
        float: right;
    }

    &:hover {
        // Switch to white icons on hover
        [class^="icon-"] {
            background-image: url("../img/glyphicons-halflings-white.png");
        }
    }
}

How to install Openpyxl with pip

(optional) Install git for windows (https://git-scm.com/) to get git bash. Git bash is much more similar to Linux terminal than Windows cmd.

Install Anaconda 3

https://www.anaconda.com/download/

It should set itself into Windows PATH. Restart your PC. Then pip should work in your cmd

Then in cmd (or git bash), run command

pip install openpyxl

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

How to keep Docker container running after starting services?

Capture the PID of the ngnix process in a variable (for example $NGNIX_PID) and at the end of the entrypoint file do

wait $NGNIX_PID 

In that way, your container should run until ngnix is alive, when ngnix stops, the container stops as well

VB.Net: Dynamically Select Image from My.Resources

This works for me at runtime too:

UltraPictureBox1.Image = My.Resources.MyPicture

No strings involved and if I change the name it is automatically updated by refactoring.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

How to reload .bash_profile from the command line?

I use Debian and I can simply type exec bash to achieve this. I can't say if it will work on all other distributions.

How can I convert a date to GMT?

I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.

getCurrentDate() {
    var date = new Date();
    var newDate = new Date(8 * 60 * 60000 + date.valueOf() + 
                           (date.getTimezoneOffset() * 60000));
    var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
    var strDate = newDate + '';
    return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}

MemoryStream - Cannot access a closed Stream

The problem is this block:

using (var sr = new StreamReader(ms))
{
    Console.WriteLine(sr.ReadToEnd());                        
}

When the StreamReader is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream is closed. When the StreamWriter gets closed, it tries to flush everything to the MemoryStream, but it is closed.

You should consider not putting the StreamReader in a using block.

Converting Secret Key into a String and Vice Versa

Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:

  1. *.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html

  2. Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

  3. Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html

Code snippets: For encoding:

String temp = new String(Base64.getEncoder().encode(key.getEncoded()));

For decoding:

byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

How can I check if a background image is loaded?

Something like this:

var $div = $('div'),
  bg = $div.css('background-image');
  if (bg) {
    var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
      $img = $('<img>').attr('src', src).on('load', function() {
        // do something, maybe:
        $div.fadeIn();
      });
  }
});

sql set variable using COUNT

You can select directly into the variable rather than using set:

DECLARE @times int

SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

If you need to set multiple variables you can do it from the same select (example a bit contrived):

DECLARE @wins int, @losses int

SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
FROM thetable
WHERE Playername='Me'

If you are partial to using set, you can use parentheses:

DECLARE @wins int, @losses int

SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
FROM thetable
WHERE Playername='Me');

Writing a string to a cell in excel

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlTest"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />
</Window>

File opens instead of downloading in internet explorer in a href link

Zip your file (.zip) and IE will give the user the option to open or download the file.

How do I divide in the Linux console?

echo 5/2 | bc -l

2.50000000000000000000

this '-l' option in 'bc' allows floating results

Padding between ActionBar's home icon and title

I used this method setContentInsetsAbsolute(int contentInsetLeft, int contentInsetRight) and it works!

int padding = getResources().getDimensionPixelSize(R.dimen.toolbar_content_insets);
mToolbar.setContentInsetsAbsolute(padding, 0);

How to flush route table in windows?

route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

Fill remaining vertical space with CSS using display:flex

Here is the codepen demo showing the solution:

Important highlights:

  • all containers from html, body, ... .container, should have the height set to 100%
  • introducing flex to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
    • if only one cell is set to flex, for example: flex: 1 then this flex item will occupy the remaining of the space
    • if there are more than one with the flex property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1 and the item 2 is se to flex: 2 then the item 2 will take twice more of the remaining space
  • Main Size Property

Could not find an implementation of the query pattern

You must have forgotten to add a using statement to the file like this:

using System.Linq;

Replace Div with another Div

HTML

<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>

JavaScript

jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));

How to automatically redirect HTTP to HTTPS on Apache servers?

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

Spring: @Component versus @Bean

  1. @Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
  2. @Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
  3. @Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as the bean name.
  4. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
  5. We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
  6. @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

Rotating videos with FFmpeg

If you don't want to re-encode your video AND your player can handle rotation metadata you can just change the rotation in the metadata using ffmpeg:

ffmpeg -i input.m4v -map_metadata 0 -metadata:s:v rotate="90" -codec copy output.m4v

adb command not found in linux environment

adb is in android-sdks/tools directory. You simply type this command: adb logcat.

If you want to your stack traces in a text file use this command: adb logcat > trace.txt. Now your traces are copied into that file.

If it is not working then go to android-sdks/platform-tools then put this command: ./adb logcat > trace.txt. Hope it will helps to you.

Changing date format in R

Using one line to convert the dates to preferred format:

nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")

How do I determine whether my calculation of pi is accurate?

You could try computing sin(pi/2) (or cos(pi/2) for that matter) using the (fairly) quickly converging power series for sin and cos. (Even better: use various doubling formulas to compute nearer x=0 for faster convergence.)

BTW, better than using series for tan(x) is, with computing say cos(x) as a black box (e.g. you could use taylor series as above) is to do root finding via Newton. There certainly are better algorithms out there, but if you don't want to verify tons of digits this should suffice (and it's not that tricky to implement, and you only need a bit of calculus to understand why it works.)

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

How to know elastic search installed version from kibana?

You can check version of ElasticSearch by the following command. It returns some other information also:

curl -XGET 'localhost:9200'

{
  "name" : "Forgotten One",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.3.4",
    "build_hash" : "e455fd0c13dceca8dbbdbb1665d068ae55dabe3f",
    "build_timestamp" : "2016-06-30T11:24:31Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.0"
  },
  "tagline" : "You Know, for Search"
}

Here you can see the version number: 2.3.4

Typically Kibana is installed in /opt/logstash/bin/kibana . So you can get the kibana version as follows

/opt/kibana/bin/kibana --version

How to resolve "Input string was not in a correct format." error?

Replace with

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Difference between StringBuilder and StringBuffer

StringBuilder and StringBuffer are almost the same. The difference is that StringBuffer is synchronized and StringBuilder is not. Although, StringBuilder is faster than StringBuffer, the difference in performance is very little. StringBuilder is a SUN's replacement of StringBuffer. It just avoids synchronization from all the public methods. Rather than that, their functionality is the same.

Example of good usage:

If your text is going to change and is used by multiple threads, then it is better to use StringBuffer. If your text is going to change but is used by a single thread, then use StringBuilder.

Draw a connecting line between two elements

JointJS/Rappid supports this use case with its Kitchensink example which supports dragging and dropping of elements, and repositioning of connections. It has many examples.

This answer is based off of Vainbhav Jain's answer.

Eclipse : Maven search dependencies doesn't work

Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.

Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.

After downloading completely, artifact searching will be ready to use.

Maven Settings

UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.

In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.

A 66M index file will be downloaded.

Maven Repositories -> Rebuild Index

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

what may be happening is your company decrypts certain traffic and re-encrypts it with their certificate (which you probably already have in your keychain or trusted root certificates)

if you're using node 7 or later I've found this fix to be compatible with node and node-gyp (for Windows you'll need to do this differently, but you basically just need to add this environment variable):

export NODE_EXTRA_CA_CERTS="absolute_path_to_your_certificates.pem" (in Windows you may need to remove the quotes - see comments)

the pem file can have multiple certificates: https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file

make sure your certificates are in proper pem format (you need real line breaks not literal \n)

I couldn't seem to get it to work with relative paths (. or ~)

This fix basically tells npm and node-gyp to use the check against the regular CAs, but also allow this certificate when it comes across it

Ideally you would be able to use your system's trusted certificates, but unfortunately this is not the case.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

To create user for phpMyAdmin :

sudo mysql -p -u root

Now you can add a new MySQL user with the username of your choice.

CREATE USER 'USERNAME'@'%' IDENTIFIED BY 'PASSWORD';

And finally grant superuser privileges to the user you just created.

GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'%' WITH GRANT OPTION;

For any question, please leave a comment

Breaking out of a for loop in Java

break; is what you need to break out of any looping statement like for, while or do-while.

In your case, its going to be like this:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

Uninstall / remove a Homebrew package including all its dependencies

EDIT:

It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree.

To install and use, issue the following commands:

$ brew tap beeftornado/rmtree
$ brew rmtree <package>

See the above link for more information and discussion.


Original answer:

It appears that currently, there's no easy way to accomplish this.

However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.

There's an external command called brew leaves which prints all packages that are not dependencies of other packages.

If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this).


EDIT: Somebody just suggested a very similar solution, using join instead of xargs:

brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))

See the comment on the issue mentioned above for more info.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Access a JavaScript variable from PHP

try adding this to your js function:

    var outputvar = document.getElementById("your_div_id_inside_html_form");
    outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';

Later in html:

    <div id="id_you_choosed_for_outputvar"></div>

this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.

In your specific geolocation case you can try adding the following to function showPosition(position):

    var outputlon = document.getElementById("lon1");
    outputlon.innerHTML = '<input id=lon value='+lon+'>';
    var outputlat = document.getElementById("lat1");
    outputlat.innerHTML = '<input id=lat value='+lat+'>';  

later add these div to your html form:

<div id=lat1></div>
<div id=lon1></div>

In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.

Hope this will help.

Get full path of the files in PowerShell

Really annoying thing in PS 5, where $_ won't be the full path within foreach. These are the string versions of FileInfo and DirectoryInfo objects. For some reason a wildcard in the path fixes it, or use Powershell 6 or 7. You can also pipe to get-item in the middle.

Get-ChildItem -path C:\WINDOWS\System32\*.txt -Recurse | foreach { "$_" }

Get-ChildItem -path C:\WINDOWS\System32 -Recurse | get-item | foreach { "$_" }

This seems to have been an issue with .Net that got resolved in .Net Core (Powershell 7): Stringification behavior of FileInfo / Directory instances has changed since v6.0.2 #7132

Printing the last column of a line in a file

One way using awk:

tail -f file.txt | awk '/A1/ { print $NF }'

append multiple values for one key in a dictionary

You can use setdefault.

for line in list:  
    d.setdefault(year, []).append(value)

This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the dictionary itself. If that makes any sense.

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

Creating temporary files in bash

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)

Compare one String with multiple values in one expression

Apache Commons Collection class.

StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)

So in your case, it would be

StringUtils.equalsAny(str, "val1", "val2", "val3");

Converting a Java Keystore into PEM Format

The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

The simplest way is to use: Request::url();

But here is a complex way:

URL::to('/').'/'.Route::getCurrentRoute()->getPath();

How can I use UIColorFromRGB in Swift?

Here's a Swift version of that function (for getting a UIColor representation of a UInt value):

func UIColorFromRGB(rgbValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

view.backgroundColor = UIColorFromRGB(0x209624)

Android LinearLayout : Add border with shadow around a LinearLayout

That's why CardView exists. CardView | Android Developers
It's just a FrameLayout that supports elevation in pre-lollipop devices.

<android.support.v7.widget.CardView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardUseCompatPadding="true"
    app:cardElevation="4dp"
    app:cardCornerRadius="3dp" >

    <!-- put whatever you want -->

</android.support.v7.widget.CardView>

To use this you need to add dependency to build.gradle:

compile 'com.android.support:cardview-v7:23.+'

CASE .. WHEN expression in Oracle SQL

It will be easier to do using decode.

SELECT
  status,
    decode ( status, 'a1','Active',
                     'a2','Active',
                     'a3','Active',
                     'i','Inactive',
                     't','Terminated',
                     'Default')STATUSTEXT
FROM STATUS

How do I execute a Shell built-in command with a C function?

You should execute sh -c echo $PWD; generally sh -c will execute shell commands.

(In fact, system(foo) is defined as execl("sh", "sh", "-c", foo, NULL) and thus works for shell built-ins.)

If you just want the value of PWD, use getenv, though.

Path of currently executing powershell script

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

React.js: Set innerHTML vs dangerouslySetInnerHTML

You can bind to dom directly

<div dangerouslySetInnerHTML={{__html: '<p>First &middot; Second</p>'}}></div>

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

Case in Select Statement

The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.

http://msdn.microsoft.com/en-us/library/ms181765.aspx

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
  CASE 
     WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
     WHEN ListPrice < 50 THEN 'Under $50'
     WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
     WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
     ELSE 'Over $1000'
  END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.

Unzipping files

I wrote a class for that too. http://blog.another-d-mention.ro/programming/read-load-files-from-zip-in-javascript/ You can load basic assets such as javascript/css/images directly from the zip using class methods. Hope it helps

Unable to merge dex

For me it was updating the firebase messaging in app\build.gradle:

compile 'com.google.firebase:firebase-messaging:10.0.1'

to

compile 'com.google.firebase:firebase-messaging:11.4.2'

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Would not creating a UserJsonResponse class and populating with the wanted fields be a cleaner solution?

Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.

In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.

What's the difference between "Solutions Architect" and "Applications Architect"?

In my experience, when I was consulting at Computer Associates, the marketing cry was 'sell solutions, not products'. Therefore, when we got a project and I needed to put on my architect's hat, I would be a Solutions Architect, as I would be designing a solution that would use a number of components, primarily CA products, and possibly some 3rd party or hand coded elements.

Now I am more focused as a developer, I am an architect of applications themselves, therefore I am an Applications Architect.

That's how I see it, however as has already been discussed, there is little in the way of naming standards.

Passing null arguments to C# methods

Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?

e.g.

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

Assign output of os.system to a variable and prevent it from being displayed on the screen

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.


Here's the corresponding code for subprocess:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out

How can I display a pdf document into a Webview?

Download source code from here (Open pdf in webview android)

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView
        android:layout_width="match_parent"
        android:background="#ffffff"
        android:layout_height="match_parent"
        android:id="@+id/webview"></WebView>
</RelativeLayout>

MainActivity.java

package com.pdfwebview;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView webview;
    ProgressDialog pDialog;

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

    init();
    listener();
    }

    private void init() {

        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");

    }

    private void listener() {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}

Polling the keyboard (detect a keypress) in python

From the comments:

import msvcrt # built-in module

def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0

Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:

#include <conio.h>

int kb_inkey () {
   int rc;
   int key;

   key = _kbhit();

   if (key == 0) {
      rc = 0;
   } else {
      rc = _getch();
   }

   return rc;
}

And I access it in python using the ctypes module (built into python 2.5):

import ctypes
import time

#
# first, load the DLL
#


try:
    kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
    raise ("Error Loading PyKeyboardAccess.dll")


#
# now, find our function
#

try:
    kbfunc = kblib.kb_inkey
except:
    raise ("Could not find the kb_inkey function in the dll!")


#
# Ok, now let's demo the capability
#

while 1:
    x = kbfunc()

    if x != 0:
        print "Got key: %d" % x
    else:
        time.sleep(.01)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Lightweight workflow engine for Java

I'd recommend you yo use an out-of-the-box solution. Given that the development of a workflow engine requires a vast amount of resources and time, a ready-made engine is a better option. Have a look at Workflow Engine. It's a lightweight component that enables you to add custom executable workflows of any complexity to any Java solutions.

AngularJS : How do I switch views from a controller function?

There are two ways for this:

If you are using ui-router or $stateProvider, do it as:

$state.go('stateName'); //remember to add $state service in the controller

if you are using angular-router or $routeProvider, do it as:

$location.path('routeName'); //similarily include $location service in your controller

How do I get textual contents from BLOB in Oracle SQL

Use this SQL to get the first 2000 chars of the BLOB.

SELECT utl_raw.cast_to_varchar2(dbms_lob.substr(<YOUR_BLOB_FIELD>,2000,1)) FROM <YOUR_TABLE>;

Note: This is because, Oracle will not be able to handle the conversion of BLOB that is more than length 2000.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

To simply explain the difference,

  response.sendRedirect("login.jsp");

doesn't prepend the contextpath (refers to the application/module in which the servlet is bundled)

but, whereas

 request.getRequestDispathcer("login.jsp").forward(request, response);

will prepend the contextpath of the respective application

Furthermore, Redirect request is used to redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url.

Forward request is used to forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How to assign name for a screen?

To create a new screen with the name foo, use

screen -S foo

Then to reattach it, run

screen -r foo  # or use -x, as in
screen -x foo  # for "Multi display mode" (see the man page)

Child inside parent with min-height: 100% not inheriting height

Add height: 1px to parent container. Works in Chrome, FF, Safari.

Change Project Namespace in Visual Studio

Just right click on the name you want to change (this could be namespace or whatever else) and select Refactor->Rename...

Enter new name, leave location as [Global Namespace], check preview if you want and you're done!

Sorting HashMap by values

package com.naveen.hashmap;

import java.util.*;
import java.util.Map.Entry;

public class SortBasedonValues {

    /**
     * @param args
     */
    public static void main(String[] args) {

        HashMap<String, Integer> hm = new HashMap<String, Integer>();
        hm.put("Naveen", 2);
        hm.put("Santosh", 3);
        hm.put("Ravi", 4);
        hm.put("Pramod", 1);
        Set<Entry<String, Integer>> set = hm.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                set);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        for (Entry<String, Integer> entry : list) {
            System.out.println(entry.getValue());

        }

    }
}

TypeScript static classes

You can also use keyword namespace to organize your variables, classes, methods and so on. See doc

namespace Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }

    const lettersRegexp = /^[A-Za-z]+$/;
    const numberRegexp = /^[0-9]+$/;

    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }

    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

Python assigning multiple variables to same value? list behavior

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

b = a[:] # this does a shallow copy, which is good enough for this case
import copy
c = copy.deepcopy(a) # this does a deep copy, which matters if the list contains mutable objects

Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can just check for null:

if(Request.QueryString["aspxerrorpath"]!=null)
{
   //your code that depends on aspxerrorpath here
}

java: How can I do dynamic casting of a variable from one type to another?

You'll need to write sort of ObjectConverter for this. This is doable if you have both the object which you want to convert and you know the target class to which you'd like to convert to. In this particular case you can get the target class by Field#getDeclaringClass().

You can find here an example of such an ObjectConverter. It should give you the base idea. If you want more conversion possibilities, just add more methods to it with the desired argument and return type.

Python Web Crawlers and "getting" html source code

If you are using Python > 3.x you don't need to install any libraries, this is directly built in the python framework. The old urllib2 package has been renamed to urllib:

from urllib import request

response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)

OpenJDK availability for Windows OS

You can find the thoroughly tested OpenJDK releases provided by Oracle at http://jdk.java.net .

For example, ready to use builds of OpenJDK 10.0.2 from Oracle for 64-bit Linux, MacOS and Windows can be found at http://jdk.java.net/10/ .

Parallel foreach with asynchronous lambda

I've created an extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
    {
        if (maxDegreeOfParallelism.HasValue)
        {
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
            {
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                {
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                    {
                        await action(item).ContinueWith(res =>
                        {
                            // action is completed, so decrement the number of currently running tasks
                            semaphoreSlim.Release();
                        });
                    }));
                }

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            }
        }
        else
        {
            await Task.WhenAll(enumerable.Select(item => action(item)));
        }
    }

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
    {
        await SomeAsyncMethod(item);
    },
    5);

How to target the href to div

havent tried but this might help

$(document).ready(function(){
r=0;s=-1;
$(a).click(function(){
v=$(this).html();
$(a).each(function(){
if($(this).html()==v)
return;
else ++r;
$(div).each(function(){
if(s==r)
$(div).appendTo($(".target")); 
++S;
});

});

});

});

Namespace not recognized (even though it is there)

Perhaps the project's type table is in an incorrect state. I would try to remove/add the reference and if that didn't work, create another project, import my code, and see if that works.

I ran into this while using VS 2005, one would expect MS to have fixed that particular problem by now though..

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

How to use a PHP class from another file?

Use include_once instead.
This error means that you have already included this file.

include_once(LIB.'/class.php');

Selenium and xPath - locating a link by containing text

Use this

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]

What is the difference between null and undefined in JavaScript?

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.

typeof(a)
//object

null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

Table 'performance_schema.session_variables' doesn't exist

Follow these steps without -p :

  1. mysql_upgrade -u root
  2. systemctl restart mysqld

I had the same problem and it works!

How to send a pdf file directly to the printer using JavaScript?

Try this: Have a button/link which opens a webpage (in a new window) with just the pdf file embedded in it, and print the webpage.

In head of the main page:

<script type="text/javascript">
function printpdf() 
{
myWindow=window.open("pdfwebpage.html");
myWindow.close;  //optional, to close the new window as soon as it opens
//this ensures user doesn't have to close the pop-up manually
}
</script>

And in body of the main page:

<a href="printpdf()">Click to Print the PDF</a>

Inside pdfwebpage.html:

<html>
<head>    
</head>

<body onload="window.print()">
<embed src="pdfhere.pdf"/>

</body>
</html>