Programs & Examples On #Dosbox

x86 Emulator for old PC applications

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

Calculating the sum of two variables in a batch script

@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number? 
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL

How can I set the PATH variable for javac so I can manually compile my .java works?

Follow the steps given here

http://www.javaandme.com/

after setting variable, just navigate to your java file directory in your cmd and type javac "xyx.java"

or if you don't navigate to the directory, then simply specify the full path of java file

javac "/xyz.java"

Reading/parsing Excel (xls) files with Python

I highly recommend xlrd for reading .xls files.

voyager mentioned the use of COM automation. Having done this myself a few years ago, be warned that doing this is a real PITA. The number of caveats is huge and the documentation is lacking and annoying. I ran into many weird bugs and gotchas, some of which took many hours to figure out.

UPDATE: For newer .xlsx files, the recommended library for reading and writing appears to be openpyxl (thanks, Ikar Pohorský).

How do I run SSH commands on remote system using Java?

I created solution based on JSch library:

import com.google.common.io.CharStreams
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session

import static java.util.Arrays.asList

class RunCommandViaSsh {

    private static final String SSH_HOST = "test.domain.com"
    private static final String SSH_LOGIN = "username"
    private static final String SSH_PASSWORD = "password"

    public static void main() {
        System.out.println(runCommand("pwd"))
        System.out.println(runCommand("ls -la"));
    }

    private static List<String> runCommand(String command) {
        Session session = setupSshSession();
        session.connect();

        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        try {
            channel.setCommand(command);
            channel.setInputStream(null);
            InputStream output = channel.getInputStream();
            channel.connect();

            String result = CharStreams.toString(new InputStreamReader(output));
            return asList(result.split("\n"));

        } catch (JSchException | IOException e) {
            closeConnection(channel, session)
            throw new RuntimeException(e)

        } finally {
            closeConnection(channel, session)
        }
    }

    private static Session setupSshSession() {
        Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
        session.setPassword(SSH_PASSWORD);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
        return session;
    }

    private static void closeConnection(ChannelExec channel, Session session) {
        try {
            channel.disconnect()
        } catch (Exception ignored) {
        }
        session.disconnect()
    }
}

What should I do when 'svn cleanup' fails?

I just removed the file svn-xxxxxxxx from the ~\.svn\tmp folder, where xxxxxxxx is a number.

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

Which Android IDE is better - Android Studio or Eclipse?

From the Android Studio download page:

Caution: Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plugin).

Prompt Dialog in Windows Forms

Based on the work of Bas Brekelmans above, I have also created two derivations -> "input" dialogs that allow you to receive from the user both a text value and a boolean (TextBox and CheckBox):

public static class PromptForTextAndBoolean
{
    public static string ShowDialog(string caption, string text, string boolStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
        Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(ckbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
    }
}

...and text along with a selection of one of multiple options (TextBox and ComboBox):

public static class PromptForTextAndSelection
{
    public static string ShowDialog(string caption, string text, string selStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
        ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
        cmbx.Items.Add("Dark Grey");
        cmbx.Items.Add("Orange");
        cmbx.Items.Add("None");
        Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(selLabel);
        prompt.Controls.Add(cmbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
    }
}

Both require the same usings:

using System;
using System.Windows.Forms;

Call them like so:

Call them like so:

PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing"); 

PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");

What is the canonical way to trim a string in Ruby without creating a new string?

Btw, now ruby already supports just strip without "!".

Compare:

p "abc".strip! == " abc ".strip!  # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip    # true

Also it's impossible to strip without duplicates. See sources in string.c:

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Update 1: As I see now -- it was created in 1999 year (see rev #372 in SVN):

Update2: strip! will not create duplicates — both in 1.9.x, 2.x and trunk versions.

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

How to upgrade docker container after its image changed

After evaluating the answers and studying the topic I'd like to summarize.

The Docker way to upgrade containers seems to be the following:

Application containers should not store application data. This way you can replace app container with its newer version at any time by executing something like this:

docker pull mysql
docker stop my-mysql-container
docker rm my-mysql-container
docker run --name=my-mysql-container --restart=always \
  -e MYSQL_ROOT_PASSWORD=mypwd -v /my/data/dir:/var/lib/mysql -d mysql

You can store data either on host (in directory mounted as volume) or in special data-only container(s). Read more about it

Upgrading applications (eg. with yum/apt-get upgrade) within containers is considered to be an anti-pattern. Application containers are supposed to be immutable, which shall guarantee reproducible behavior. Some official application images (mysql:5.6 in particular) are not even designed to self-update (apt-get upgrade won't work).

I'd like to thank everybody who gave their answers, so we could see all different approaches.

Remove all items from a FormArray in Angular

You can easily define a getter for your array and clear it as follows:

  formGroup: FormGroup    
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      sliders: this.fb.array([])
    })
  }
  get sliderForms() {
    return this.formGroup.get('sliders') as FormArray
  }

  clearAll() {
    this.formGroup.reset()
    this.sliderForms.clear()
  }

How to read from stdin line by line in Node

// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());

How to create a temporary directory/folder in Java?

I like the multiple attempts at creating a unique name but even this solution does not rule out a race condition. Another process can slip in after the test for exists() and the if(newTempDir.mkdirs()) method invocation. I have no idea how to completely make this safe without resorting to native code, which I presume is what's buried inside File.createTempFile().

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

First of all, this problem exists because of network issues, and uninstalling and re-installing everything won't be of much help. Probably you are behind proxy, and in that case you need to set proxy.

But in my case, I was facing the problem because I wasn't behind proxy. Generally, I work behind proxy, but when working from home, I set the proxy to None in Network settings.

But I was still getting the same errors even after removing the proxy settings.

So, when I did type

env | grep proxy

I found something like this :

http_proxy=http://127.0.0.1:1234/

And this was the reason I was still getting the very same error, even when I thought I had removed the proxy settings.

To unset this proxy, type

unset http_proxy

Follow the same approach for all the other entries, such as https_proxy.

Checking if form has been submitted - PHP

Actually, the submit button already performs this function.

Try in the FORM:

<form method="post">
<input type="submit" name="treasure" value="go!">
</form>

Then in the PHP handler:

if (isset($_POST['treasure'])){
echo "treasure will be set if the form has been submitted (to TRUE, I believe)";
}

OOP vs Functional Programming vs Procedural

These paradigms don't have to be mutually exclusive. If you look at python, it supports functions and classes, but at the same time, everything is an object, including functions. You can mix and match functional/oop/procedural style all in one piece of code.

What I mean is, in functional languages (at least in Haskell, the only one I studied) there are no statements! functions are only allowed one expression inside them!! BUT, functions are first-class citizens, you can pass them around as parameters, along with a bunch of other abilities. They can do powerful things with few lines of code.

While in a procedural language like C, the only way you can pass functions around is by using function pointers, and that alone doesn't enable many powerful tasks.

In python, a function is a first-class citizen, but it can contain arbitrary number of statements. So you can have a function that contains procedural code, but you can pass it around just like functional languages.

Same goes for OOP. A language like Java doesn't allow you to write procedures/functions outside of a class. The only way to pass a function around is to wrap it in an object that implements that function, and then pass that object around.

In Python, you don't have this restriction.

What is the best alternative IDE to Visual Studio

There's MonoDevelop, which I occasionally use when I want to do some light C# coding when in Linux. It's nothing close to VS.Net, but it works for small projects. I really don't think most of the alternatives people have listed come anywhere close to VS.Net.

Loading basic HTML in Node.js

You could also use this snippet:

var app = require("express");
app.get('/', function(req,res){
   res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);

Plain Old CLR Object vs Data Transfer Object

POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.

Whether a POCO has behaviour or not it's immaterial.

A DTO may be POCO as may a domain object (which would typically be rich in behaviour).

Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.

In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

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

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel]
"Connection Settings"=dword:00000000
"Connwiz Admin Lock"=dword:00000000
"Autoconfig"=dword:00000000
"Proxy"=dword:00000000
"ConnectionsTab"=dword:00000000

Positioning background image, adding padding

There is actually a native solution to this, using the four-values to background-position

.CssClass {background-position: right 10px top 20px;}

This means 10px from right and 20px from top. you can also use three values the fourth value will be count as 0.

UILabel with text of two different colors

Here you go

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:lblTemp.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
lblTemp.attributedText = string;

How to display pie chart data values of each slice in chart.js

From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:

function drawSegmentValues()
{
    for(var i=0; i<myPieChart.segments.length; i++) 
    {
        // Default properties for text (size is scaled)
        ctx.fillStyle="white";
        var textSize = canvas.width/10;
        ctx.font= textSize+"px Verdana";

        // Get needed variables
        var value = myPieChart.segments[i].value;
        var startAngle = myPieChart.segments[i].startAngle;
        var endAngle = myPieChart.segments[i].endAngle;
        var middleAngle = startAngle + ((endAngle - startAngle)/2);

        // Compute text location
        var posX = (radius/2) * Math.cos(middleAngle) + midX;
        var posY = (radius/2) * Math.sin(middleAngle) + midY;

        // Text offside to middle of text
        var w_offset = ctx.measureText(value).width/2;
        var h_offset = textSize/4;

        ctx.fillText(value, posX - w_offset, posY + h_offset);
    }
}

A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.

In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.

Fiddle Example


With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:

Math.round(myPieChart.segments[i].value/totalValue*100)+'%';

The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:

var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
    value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';

Fiddle Example of percentile with decimals

Fiddle Example of percentile with integers

How to Iterate over a Set/HashSet without an Iterator?

Converting your set into an array may also help you for iterating over the elements:

Object[] array = set.toArray();

for(int i=0; i<array.length; i++)
   Object o = array[i];

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

pod install -bash: pod: command not found

Installing CocoaPods on OS X 10.11

These instructions were tested on all betas and the final release of El Capitan.

Custom GEM_HOME

This is the solution when you are receiving above error

$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version
0.38.2

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

PHP: check if any posted vars are empty - form: all fields required

if( isset( $_POST['login'] ) &&  strlen( $_POST['login'] ))
{
  // valid $_POST['login'] is set and its value is greater than zero
}
else
{
  //error either $_POST['login'] is not set or $_POST['login'] is empty form field
}

NPM doesn't install module dependencies

happens with old node version. use latest version of node like this:

$ nvm use 8.0
$ rm -rf node_modules
$ npm install
$ npm i somemodule

edit: also make sure you save.
eg: npm install yourmoduleName --save

"Auth Failed" error with EGit and GitHub

For existing ssh keys, I think that it's a bug in Eclipse Juno 3.8.

What I did:

1) Load the existing key by going to: Window > Preferences > "Search ssh" > Key Management Tab > Load Existing Key > Select the private key which you already have

2) Save that key by clicking the button Save Private Key. Let's name it id_dsa_github

3) Now check if push and pull are working or not. It should be.

4) Now in the general tab, remove the private key id_dsa_github and add your previous private key by clicking the button Add private key

Now you are good to go. It's taking at least one time to do all the things from EGit to register, I guess.

Send email using the GMail SMTP server from a PHP page

I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.

Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.

Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own.

Support servers that require username & password and/or encryption.

Protect from header injection attacks without stripping request data content.

Send MIME compliant HTML/multipart emails.

Use event-driven plugins to customize the library.

Handle large attachments and inline/embedded images with low memory use.

It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).

The working example of Gmail SSL/SMTP and Swift Mailer is here...

// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';

// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
    ->setUsername('[email protected]') // Your Gmail Username
    ->setPassword('my_secure_gmail_password'); // Your Gmail Password

// Mailer
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
    ->setFrom(array('[email protected]' => 'Sender Name')) // can be $_POST['email'] etc...
    ->setTo(array('[email protected]' => 'Receiver Name')) // your email / multiple supported.
    ->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');

// Send the message
if ($mailer->send($message)) {
    echo 'Mail sent successfully.';
} else {
    echo 'I am sure, your configuration are not correct. :(';
}

I hope this helps. Happy coding... :)

Make multiple-select to adjust its height to fit options without scroll bar

The way a select box is rendered is determined by the browser itself. So every browser will show you the height of the option list box in another height. You can't influence that. The only way you can change that is to make an own select from the scratch.

Difference between Spring MVC and Struts MVC

The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.

Send parameter to Bootstrap modal window?

I have found this better way , no need to remove data , just call the source of the remote content each time

$(document).ready(function() {
    $('.class').click(function() {
        var id = this.id;
        //alert(id);checking that have correct id
        $("#iframe").attr("src","url?id=" + id);
        $('#Modal').modal({ 
            show: true 
        });
    });
});

cURL error 60: SSL certificate: unable to get local issuer certificate

Guzzle, which is used by cartalyst/stripe, will do the following to find a proper certificate archive to check a server certificate against:

  1. Check if openssl.cafile is set in your php.ini file.
  2. Check if curl.cainfo is set in your php.ini file.
  3. Check if /etc/pki/tls/certs/ca-bundle.crt exists (Red Hat, CentOS, Fedora; provided by the ca-certificates package)
  4. Check if /etc/ssl/certs/ca-certificates.crt exists (Ubuntu, Debian; provided by the ca-certificates package)
  5. Check if /usr/local/share/certs/ca-root-nss.crt exists (FreeBSD; provided by the ca_root_nss package)
  6. Check if /usr/local/etc/openssl/cert.pem (OS X; provided by homebrew)
  7. Check if C:\windows\system32\curl-ca-bundle.crt exists (Windows)
  8. Check if C:\windows\curl-ca-bundle.crt exists (Windows)

You will want to make sure that the values for the first two settings are properly defined by doing a simple test:

echo "openssl.cafile: ", ini_get('openssl.cafile'), "\n";
echo "curl.cainfo: ", ini_get('curl.cainfo'), "\n";

Alternatively, try to write the file into the locations indicated by #7 or #8.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Ternary operator ?: vs if...else

Ternary Operator always returns a value. So in situation when you want some output value from result and there are only 2 conditions always better to use ternary operator. Use if-else if any of the above mentioned conditions are not true.

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

I have used a trick to handle the apostrophe special character. When replacing ' for \' you need to place four backslashes before the apostrophe.

str.replaceAll("'","\\\\'");

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

ORA-28001: The password has expired

I had same problem, i am trying to login database it appear a message with: "ORA-28001: The password has expired" , I have fixed the problem simple steps

1.open command prompt 2.type sqlplus 3.It will ask Enter Password, you can give old password, it will show password has expired ORA-28001 4.It will ask new password and retype password 5.It will change with new password 6.Go to the sql database and try to connect with new password, it will connect.

IIS Config Error - This configuration section cannot be used at this path

When I tried these steps I kept getting error:

  1. Search for "Turn windows features on or off"
  2. Check "Internet Information Services"
  3. Check "World Wide Web Services"
  4. Check "Application Development Features"
  5. Enable all items under this

Then i looked at event viewer and saw this error:Unable to install counter strings because the SYSTEM\CurrentControlSet\Services\ASP.NET_64\Performance key could not be opened or accessed. The first DWORD in the Data section contains the Win32 error code.

To fix the issue i manually created following entry in registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ASP.NET_64\Performance

and followed these steps:

  1. Search for "Turn windows features on or off"
  2. Check "Internet Information Services"
  3. Check "World Wide Web Services"
  4. Check "Application Development Features"
  5. Enable all items under this

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

How to import cv2 in python3?

anaconda prompt -->pip install opencv-python

How to add MVC5 to Visual Studio 2013?

Go File -> New Project.

Select Web under Visual C#.

Select ASP.NET Web Application

select mvc

when solution is created, you will find resources getting added in solution in status bar of vs 2013.

Check property of Dll file --> system.web.mvc, it shows latest version (5.2.2.0)

but depending on your OS runtime version will be decided.

MySQL/SQL: Group by date only on a Datetime column

I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

SELECT date
FROM blog 
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC 

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

Parse large JSON file in Nodejs

I think you need to use a database. MongoDB is a good choice in this case because it is JSON compatible.

UPDATE: You can use mongoimport tool to import JSON data into MongoDB.

mongoimport --collection collection --file collection.json

Understanding dict.copy() - shallow or deep?

Contents are shallow copied.

So if the original dict contains a list or another dictionary, modifying one them in the original or its shallow copy will modify them (the list or the dict) in the other.

Delete specific line number(s) from a text file using sed?

This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;

grep -nh error logfile | cut -d: -f1 | deletelines logfile

(where deletelines is the utility you are imagining you need) is the same as

grep -v error logfile

Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed.

sed 's%$%d%' linenumbers

This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d appended after each. This is a valid sed script, which we can save to a file, or (on some platforms) pipe to another sed instance:

sed 's%$%d%' linenumbers | sed -f - logfile

On some platforms, sed -f does not understand the option argument - to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin or /proc/$pid/fd/1 if your OS (or shell) has that.

As always, you can add -i before the -f option to have sed edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i as well; a common idiom is to supply an empty argument; -i ''.

How to make an Asynchronous Method return a value?

Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.

    public void UseBackgroundWorker()
    {
        var worker = new BackgroundWorker();
        worker.DoWork += DoWork;
        worker.RunWorkerCompleted += WorkDone;
        worker.RunWorkerAsync("input");
    }

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = e.Argument.Equals("input");
        Thread.Sleep(1000);
    }

    public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
    {
        var result = (bool) e.Result;
    }

How to set caret(cursor) position in contenteditable element (div)?

  const el = document.getElementById("editable");
  el.focus()
  let char = 1, sel; // character at which to place caret

  if (document.selection) {
    sel = document.selection.createRange();
    sel.moveStart('character', char);
    sel.select();
  }
  else {
    sel = window.getSelection();
    sel.collapse(el.lastChild, char);
  }

C# DataRow Empty-check

To delete null and also empty entries Try this

  foreach (var column in drEntitity.Columns.Cast<DataColumn>().ToArray())
            {
                if (drEntitity.AsEnumerable().All(dr => dr.IsNull(column) | string.IsNullOrEmpty( dr[column].ToString())))
                    drEntitity.Columns.Remove(column);
            }

How to build an APK file in Eclipse?

Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.

How to reset sequence in postgres and fill id column with new data?

Just for simplifying and clarifying the proper usage of ALTER SEQUENCE and SELECT setval for resetting the sequence:

ALTER SEQUENCE sequence_name RESTART WITH 1;

is equivalent to

SELECT setval('sequence_name', 1, FALSE);

Either of the statements may be used to reset the sequence and you can get the next value by nextval('sequence_name') as stated here also:

nextval('sequence_name')

How do I use variables in Oracle SQL Developer?

Ok I know this a bit of a hack but this is a way to use a variable in a simple query, not a script:

WITH
    emplVar AS
    (SELECT 1234 AS id FROM dual)
SELECT
    *
FROM
    employees,
    emplVar
WHERE
    EmployId=emplVar.id;

You get to run it everywhere.

Android button background color

With version 1.2.0-alpha06 of material design library, now we can use android:background="..." on MaterialButton components:

<com.google.android.material.button.MaterialButton
    android:background="#fff"
    ...
/>

SQL Plus change current directory

I don't think you can!

/home/export/user1 $ sqlplus / 
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql

script2.sql has to be in /home/export/user1.

You either use the full path, or exit the script and start sqlplus again from the right directory.

#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql

(something like that - doing this from memory!)

javascript check for not null

It's because val is not null, but contains 'null' as a string.

Try to check with 'null'

if ('null' != val)

For an explanation of when and why this works, see the details below.

Detecting scroll direction

You can try doing this.

_x000D_
_x000D_
function scrollDetect(){_x000D_
  var lastScroll = 0;_x000D_
_x000D_
  window.onscroll = function() {_x000D_
      let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value_x000D_
_x000D_
      if (currentScroll > 0 && lastScroll <= currentScroll){_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";_x000D_
      }else{_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling UP";_x000D_
      }_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
scrollDetect();
_x000D_
html,body{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
_x000D_
.cont{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  background: #ffad33;_x000D_
}_x000D_
_x000D_
.red{_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
p{_x000D_
  position:fixed;_x000D_
  font-size:25px;_x000D_
  top:5%;_x000D_
  left:5%;_x000D_
}
_x000D_
<div class="cont">_x000D_
  <div class="item"></div>_x000D_
  <div class="item red"></div>_x000D_
  <p id="scrollLoc">0</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

File upload along with other object in Jersey restful web service

The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

As an example, here is a javascript client posting to a Jersey example service,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

enter image description here

On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

Convert string to Time

string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);

string t = date.ToString("HH:mm:ss tt");

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

How to reference a method in javadoc?

You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the

{@link package.class#member label}

tag (that you are looking for). The corresponding example from the documentation is as follows

For example, here is a comment that refers to the getComponentAt(int, int) method:

Use the {@link #getComponentAt(int, int) getComponentAt} method.

The package.class part can be ommited if the referred method is in the current class.


Other useful links about JavaDoc are:

How to find integer array size in java

I think you are confused between size() and length.

(1) The reason why size has a parentheses is because list's class is List and it is a class type. So List class can have method size().

(2) Array's type is int[], and it is a primitive type. So we can only use length

How to check if a float value is a whole number

Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.

for i in range(20, 30):
    print("Trying {0}".format(i))
    if i ** 3 > 12000:
        print("Maximum integral cube root less than 12000: {0}".format(i - 1))
        break

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Show animated GIF

I came here searching for the same answer, but based on the top answers, I came up with an easier code. Hope this will help future searches.

Icon icon = new ImageIcon("src/path.gif");
            try {
                mainframe.setContentPane(new JLabel(icon));
            } catch (Exception e) {
            }

Url.Action parameters?

Here is another simple way to do it

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>

Where is @Model.ID is a parameter

And here there is a second example.

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2&param3=ViewBag.P3'>Print</a>

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

import urllib2
for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"):
    print line

Laravel Eloquent update just if changes have been made

I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

$post = Post::find($id);    
$post->fill($request->input())->save();

keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Small addition to the help above: I got the mismatch error after adding a static libto an older VST solution using VST 2017 . VST now generates "stdfax.h" for precompiled headers containing these 2 lines:

// Turn off iterator debugging as it makes the compiler very slow on large methods in debug builds
#define _HAS_ITERATOR_DEBUGGING 0

How to get the index with the key in Python dictionary?

#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}

#Convert dictionary to list (array)
keys = list(animals)

#Printing 1st dictionary key by index
print(keys[0])

#Done :)

Can I convert long to int?

The safe and fastest way is to use Bit Masking before cast...

int MyInt = (int) ( MyLong & 0xFFFFFFFF )

The Bit Mask ( 0xFFFFFFFF ) value will depend on the size of Int because Int size is dependent on machine.

Best practices for copying files with Maven

For a simple copy-tasks I can recommend copy-rename-maven-plugin. It's straight forward and simple to use:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>com.coderplus.maven.plugins</groupId>
        <artifactId>copy-rename-maven-plugin</artifactId>
        <version>1.0</version>
        <executions>
          <execution>
            <id>copy-file</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
              <destinationFile>target/someDir/environment.properties</destinationFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

If you would like to copy more than one file, replace the <sourceFile>...</destinationFile> part with

<fileSets>
  <fileSet>
    <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
    <destinationFile>target/someDir/environment.properties</destinationFile>
  </fileSet>
  <fileSet>
    <sourceFile>src/someDirectory/test.logback.xml</sourceFile>
    <destinationFile>target/someDir/logback.xml</destinationFile>
  </fileSet>                
</fileSets>

Furthermore you can specify multiple executions in multiple phases if needed, the second goal is "rename", which simply does what it says while the rest of the configuration stays the same. For more usage examples refer to the Usage-Page.

Note: This plugin can only copy files, not directories. (Thanks to @james.garriss for finding this limitation.)

CASE in WHERE, SQL Server

You can simplify to:

WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

Equals(=) vs. LIKE

Depends on the database system.

Generally with no special characters, yes, = and LIKE are the same.

Some database systems, however, may treat collation settings differently with the different operators.

For instance, in MySQL comparisons with = on strings is always case-insensitive by default, so LIKE without special characters is the same. On some other RDBMS's LIKE is case-insensitive while = is not.

MVC 5 Access Claims Identity User Data

shortest and simplified version of @Rosdi Kasim'd answer is

string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
    FindFirst("claimname").Value;

Claimname is the claim you want to retrieve i.e if you are looking for "StreedAddress" claim then the above answer will be like this

string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
    FindFirst("StreedAddress").Value;

Convert NVARCHAR to DATETIME in SQL Server 2008

DECLARE @chr nvarchar(50) = (SELECT CONVERT(nvarchar(50), GETDATE(), 103))

SELECT @chr chars, CONVERT(date, @chr, 103) date_again

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

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

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

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

-- I like this as the data type and the format remains consistent with a date time data type

;with cte as(
    select 
        cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
    from dbo.mytable cd 
    where utcdate between '2014-01-14' and '2014-01-15'
    group by
        cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte

getResources().getColor() is deprecated

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

It is not deprecated in API Level 21, according to the documentation.

It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor() that takes the color resource ID and a Resources.Theme object) is only available in the M Developer Preview.

Hence, right now, continue using the single-parameter getColor() method. Later this year, consider using the two-parameter getColor() method on Android M devices, falling back to the deprecated single-parameter getColor() method on older devices.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Python find min max and average of a list (array)

Return min and max value in tuple:

def side_values(num_list):
    results_list = sorted(num_list)
    return results_list[0], results_list[-1]


somelist = side_values([1,12,2,53,23,6,17])
print(somelist)

How do I get the path of the Python script I am running in?

import os
print os.path.abspath(__file__)

C# How can I check if a URL exists/is valid?

Here is another option

public static bool UrlIsValid(string url)
{
    bool br = false;
    try {
        IPHostEntry ipHost = Dns.Resolve(url);
        br = true;
    }
    catch (SocketException se) {
        br = false;
    }
    return br;
}

Sorting Characters Of A C++ String

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

How do I uninstall a Windows service if the files do not exist anymore?

You can try running Autoruns, which would save you from having to edit the registry by hand. This is especially useful when you don't have the needed permissions.

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

JFrame: How to disable window resizing?

Use setResizable on your JFrame

yourFrame.setResizable(false);

But extending JFrame is generally a bad idea.

SQL Server database backup restore on lower version

You'd have to use the Import/Export wizards in SSMS to migrate everything

There is no "downgrade" possible using backup/restore or detach/attach. Therefore what you have to do is:

  1. Backup the database from the server running the new SSMS/SQL version.
  2. Import data from the generated .bak file, by expanding the "Tasks" menu(after right-clicking the target database) and selecting the "Import Data" option.

How to install Android SDK Build Tools on the command line?

Inspired from answers by @i4niac & @Aurélien Lambert, this is what i came up with

csv_update_numbers=$(./android list sdk --all | grep 'Android SDK Build-tools' | grep -v 'Obsolete' | sed 's/\(.*\)\- A.*/\1/'|sed '/^$/d'|sed -e 's/^[ \t]*//'| tr '\n' ',')
csv_update_numbers_without_trailing_comma=${csv_update_numbers%?}

( sleep 5 && while [ 1 ]; do sleep 1; echo y; done ) \
    | ./android update sdk --all -u -t $csv_update_numbers_without_trailing_comma

Explanation

  • get a comma separated list of numbers which are the indexes of build tools packages in the result of android list sdk --all command (Ignoring obsolete packages).
  • keep throwing 'y's at the terminal every few miliseconds to accept the licenses.

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....

static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";

public static void ReadExcel() {
InputStream inputStream = null;
   try {
        inputStream = new FileInputStream(new File(excelLoc));
        Workbook wb = WorkbookFactory.create(inputStream);
        int numberOfSheet = wb.getNumberOfSheets();

        for (int i = 0; i < numberOfSheet; i++) {
             Sheet sheet = wb.getSheetAt(i);
             //.... Customize your code here
             // To get sheet name, try -> sheet.getSheetName()
        }
   } catch {}
}

How to enable external request in IIS Express?

If you have tried Colonel Panic's answer but doesn't work in Visual Studio, try this:

Append another <binding /> in your IIS Express config

<bindings>
    <binding protocol="http" bindingInformation="*:8080:localhost" />
    <binding protocol="http" bindingInformation="*:8080:hostname" />
</bindings>

Finally, you have to run Visual Studio as Admin

python: after installing anaconda, how to import pandas

The cool thing about anaconda is, that you can manage virtual environments for several projects. Those also have the benefit of keeping several python installations apart. This could be a problem when several installations of a module or package are interfering with each other.

Try the following:

  1. Create a new anaconda environment with user@machine:~$ conda create -n pandas_env python=2.7
  2. Activate the environment with user@machine:~$ source activate pandas_env on Linux/OSX or $ activate pandas_env on Windows. On Linux the active environment is shown in parenthesis in front of the user name in the shell. (I am not sure how windows handles this, but you can see it by typing $ conda info -e. The one with the * next to it is the active one)
  3. Type (pandas_env)user@machine:~$ conda list to show a list of all installed modules.
  4. If pandas is missing from this list, install it (while still inside the pandas_env environment) with (pandas_env)user@machine:~$ conda install pandas, as @Fiabetto suggested.
  5. Open python (pandas_env)user@machine:~$ python and try to load pandas again.

Note that now you are working in a python environment, that only knows the modules installed inside the pandas_env environment. Every time you want to use it you have to activate the environment. This might feel a little bit clunky at first, but really shines once you have to manage different versions of python (like 2.7 or 3.4) or you need a specific version of a module (like numpy 1.7).

Edit:

If this still does not work you have several options:

  1. Check if the right pandas module is found:

    `(pandas_env)user@machine:~$ python`
    Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
    >>> import imp
    >>> imp.find_module("pandas")
    (None, '/path/to/miniconda3/envs/foo/lib/python2.7/site-packages/pandas', ('', '', 5))
    
    # See what this returns on your system.
    
  2. Reinstall pandas in your environment with $ conda install -f pandas. This might help if you files have been corrupted somehow.

  3. Install pandas from a different source (using pip). To do this, create a new environment like above (make sure to pick a different name to avoid clashes here) but replace point 4 by (pandas_env)user@machine:~$ pip install pandas.
  4. Reinstall anaconda (make sure you pick the right version 32bit / 64bit depending on your OS, this can sometimes lead to problems). It could be possible, that your 'normal' and your anaconda python are clashing. As a last resort you could try to uninstall your 'normal' python before you reinstall anaconda.

How to delete duplicates on a MySQL table?

this removes duplicates in place, without making a new table

ALTER IGNORE TABLE `table_name` ADD UNIQUE (title, SID)

note: only works well if index fits in memory

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.

Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.

Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...

<some folder>\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\xyz.h"

On the other hand let's say your file structure looks like this...

<some folder>\include\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\include\xyz.h"

Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h> you should probably change it to #include "xyz.h"

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

If input value is blank, assign a value of "empty" with Javascript

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

How to get history on react-router v4?

This works! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

Read Session Id using Javascript

For PHP's PHPSESSID variable, this function works:

function getPHPSessId() {
    var phpSessionId = document.cookie.match(/PHPSESSID=[A-Za-z0-9]+\;/i);

    if(phpSessionId == null) 
        return '';

    if(typeof(phpSessionId) == 'undefined')
        return '';

    if(phpSessionId.length <= 0)
        return '';

    phpSessionId = phpSessionId[0];

    var end = phpSessionId.lastIndexOf(';');
    if(end == -1) end = phpSessionId.length;

    return phpSessionId.substring(10, end);
}

req.body empty on posts

Make sure ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] is in your postman request headers

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I've been there too and searched everywhere how /usr/libexec/java_home works but I couldn't find any information on how it determines the available Java Virtual Machines it lists.

I've experimented a bit and I think it simply executes a ls /Library/Java/JavaVirtualMachines and then inspects the ./<version>/Contents/Info.plist of all runtimes it finds there.

It then sorts them descending by the key JVMVersion contained in the Info.plist and by default it uses the first entry as its default JVM.

I think the only thing we might do is to change the plist: sudo vi /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Info.plist and then modify the JVMVersion from 1.8.0 to something else that makes it sort it to the bottom instead of the top, like !1.8.0.

Something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    ...
    <dict>
            ...
            <key>JVMVersion</key>
            <string>!1.8.0</string>   <!-- changed from '1.8.0' to '!1.8.0' -->`

and then it magically disappears from the top of the list:

/usr/libexec/java_home -verbose
Matching Java Virtual Machines (3):
    1.7.0_45, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
    1.7.0_09, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
    !1.8.0, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home

Now you will need to logout/login and then:

java -version
java version "1.7.0_45"

:-)

Of course I have no idea if something else breaks now or if the 1.8.0-ea version of java still works correctly.

You probably should not do any of this but instead simply deinstall 1.8.0.

However so far this has worked for me.

mailto link with HTML body

I have used this and it seems to work with outlook, not using html but you can format the text with line breaks at least when the body is added as output.

<a href="mailto:[email protected]?subject=Hello world&body=Line one%0DLine two">Email me</a>

How to work with complex numbers in C?

The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.

Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...

Real and imaginary part, of a negative square root example:

#include <stdio.h>   
#include <complex.h>

int main() 
{
    int negNum;

    printf("Calculate negative square roots:\n"
           "Enter negative number:");

    scanf("%d", &negNum);

    double complex negSqrt = csqrt(negNum);

    double pReal = creal(negSqrt);
    double pImag = cimag(negSqrt);

    printf("\nReal part %f, imaginary part %f"
           ", for negative square root.(%d)",
           pReal, pImag, negNum);

    return 0;
}

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

Python's most efficient way to choose longest string in list?

What should happen if there are more than 1 longest string (think '12', and '01')?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...

To add server using sp_addlinkedserver

Add the linked server first with

exec sp_addlinkedserver
@server = 'SNRJDI\SLAMANAGEMENT',
@srvproduct=N'',
@provider=N'SQLNCLI'

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

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

XAMPP installation on Win 8.1 with UAC Warning

There's nothing to be worried upon for this. Like other servers, install xampp somewhere outside of the default Program Files folder of Windows. It shall work fine.

I previously had wamp server installed on my machine and i never understood why wamp server installs itself outside of the default directory. Xampp cleared this, now i have both the servers lying outside the Program Files folder and are running fine.

Spring: How to get parameters from POST body?

You can get param from request.

@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
            HttpServletResponse response, Model model){
   String jsonString = request.getParameter("json");
}

How do I run a VBScript in 32-bit mode on a 64-bit machine?

WScript.exe exists in two versions, one in C:\Windows\System32\ and the other in C:\Windows\SysWOW64\ directories. They run respectively in 64 bits and 32 bits (against immediate logic but true).

You may add the following code at the beginning of your script so that it automatically starts again in 32 bits if it detects that it's called in 64 bits.

Note that it transmits the arguments if it calls itself to switch to 64 bits.

' C:\Windows\System32\WScript.exe = WScript.exe
Dim ScriptHost : ScriptHost = Mid(WScript.FullName, InStrRev(WScript.FullName, "\") + 1, Len(WScript.FullName))

Dim oWs : Set oWs = CreateObject("WScript.Shell")
Dim oProcEnv : Set oProcEnv = oWs.Environment("Process")

' Am I running 64-bit version of WScript.exe/Cscript.exe? So, call script again in x86 script host and then exit.
If InStr(LCase(WScript.FullName), LCase(oProcEnv("windir") & "\System32\")) And oProcEnv("PROCESSOR_ARCHITECTURE") = "AMD64" Then
    ' rebuild arguments
    If Not WScript.Arguments.Count = 0 Then
        Dim sArg, Arg
        sArg = ""
        For Each Arg In Wscript.Arguments
              sArg = sArg & " " & """" & Arg & """"
        Next
    End If

    Dim sCmd : sCmd = """" &  oProcEnv("windir") & "\SysWOW64\" & ScriptHost & """" & " """ & WScript.ScriptFullName & """" & sArg
    'WScript.Echo "Call " & sCmd
    oWs.Run sCmd
    WScript.Quit
End If

How to round down to nearest integer in MySQL?

Use FLOOR(), if you want to round your decimal to the lower integer. Examples:

FLOOR(1.9) => 1
FLOOR(1.1) => 1

Use ROUND(), if you want to round your decimal to the nearest integer. Examples:

ROUND(1.9) => 2
ROUND(1.1) => 1

Use CEIL(), if you want to round your decimal to the upper integer. Examples:

CEIL(1.9) => 2
CEIL(1.1) => 2

How to configure heroku application DNS to Godaddy Domain?

I used this videocast to set up my GoDaddy domain with Heroku, and it worked perfectly. Very clear and well explained.

Note: Skip the part about CNAME yourdomain.com. (note the .) and the heroku addons:add "custom domains"

http://blog.heroku.com/archives/2009/10/7/heroku_casts_setting_up_custom_domains/


To summarize the video:

1) on GoDaddy and create a CNAME with

Alias Name: www
Host Name: proxy.heroku.com

2) check that your domain has propagated by typing host www.yourdomain.com on the command line

3) run heroku domains:add www.yourdomain.com

4) run heroku domains:add yourdomain.com

It worked for me after these steps. Hope it works for you too!

UPDATE: things have changed, check out this post Heroku/GoDaddy: send naked domain to www

E: Unable to locate package npm

in my jenkins/jenkins docker sudo always generates error:

bash: sudo: command not found

I needed update repo list with:

curl -sL https://deb.nodesource.com/setup_10.x | apt-get update

then,

 apt-get install nodejs

All the command line results like this:

root@76e6f92724d1:/# curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
Ign:1 http://deb.debian.org/debian stretch InRelease
Get:2 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]
Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]
Get:4 http://deb.debian.org/debian stretch Release [118 kB]
Get:5 http://security.debian.org/debian-security stretch/updates/main amd64 Packages [520 kB]
Get:6 http://deb.debian.org/debian stretch-updates/main amd64 Packages [27.9 kB]
Get:8 http://deb.debian.org/debian stretch Release.gpg [2410 B]
Get:9 http://deb.debian.org/debian stretch/main amd64 Packages [7083 kB]
Get:7 https://packagecloud.io/github/git-lfs/debian stretch InRelease [23.2 kB]
Get:10 https://packagecloud.io/github/git-lfs/debian stretch/main amd64 Packages [4675 B]
Fetched 7965 kB in 20s (393 kB/s)
Reading package lists... Done
root@76e6f92724d1:/#  apt-get install nodejs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libicu57 libuv1
The following NEW packages will be installed:
  libicu57 libuv1 nodejs
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.2 MB of archives.
After this operation, 45.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 libicu57 amd64 57.1-6+deb9u3 [7705 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 libuv1 amd64 1.9.1-3 [84.4 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 nodejs amd64 4.8.2~dfsg-1 [3440 kB]
Fetched 11.2 MB in 26s (418 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libicu57:amd64.
(Reading database ... 12488 files and directories currently installed.)
Preparing to unpack .../libicu57_57.1-6+deb9u3_amd64.deb ...
Unpacking libicu57:amd64 (57.1-6+deb9u3) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../libuv1_1.9.1-3_amd64.deb ...
Unpacking libuv1:amd64 (1.9.1-3) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../nodejs_4.8.2~dfsg-1_amd64.deb ...
Unpacking nodejs (4.8.2~dfsg-1) ...
Setting up libuv1:amd64 (1.9.1-3) ...
Setting up libicu57:amd64 (57.1-6+deb9u3) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Setting up nodejs (4.8.2~dfsg-1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode

Find nginx version?

In my case, I try to add sudo

sudo nginx -v

enter image description here

Check if one date is between two dates

Try what's below. It will help you...

Fiddle : http://jsfiddle.net/RYh7U/146/

Script :

if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
    alert("Availed");
else
    alert("Not Availed");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

enumerate() for dictionary in python

dict1={'a':1, 'b':'banana'}

To list the dictionary in Python 2.x:

for k,v in dict1.iteritems():
        print k,v 

In Python 3.x use:

for k,v in dict1.items():
        print(k,v)
# a 1
# b banana

Finally, as others have indicated, if you want a running index, you can have that too:

for i  in enumerate(dict1.items()):
   print(i)  

 # (0, ('a', 1))
 # (1, ('b', 'banana'))

But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.

How do I query using fields inside the new PostgreSQL JSON datatype?

With postgres 9.3 use -> for object access. 4 example

seed.rb

se = SmartElement.new
se.data = 
{
    params:
    [
        {
            type: 1,
            code: 1,
            value: 2012,
            description: 'year of producction'
        },
        {
            type: 1,
            code: 2,
            value: 30,
            description: 'length'
        }
    ]
}

se.save

rails c

SELECT data->'params'->0 as data FROM smart_elements;

returns

                                 data
----------------------------------------------------------------------
 {"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)

You can continue nesting

SELECT data->'params'->0->'type' as data FROM smart_elements;

return

 data
------
 1
(1 row)

Passing javascript variable to html textbox

Pass the variable to the form element like this

your form element

<input type="text" id="mytext">

javascript

var test = "Hello";
document.getElementById("mytext").value = test;//Now you get the js variable inside your form element

Which MySQL data type to use for storing boolean values

Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use

bool_val TINYINT CHECK(bool_val IN(0,1))

You will only be able to store 0, 1 or NULL, as well as values which can be converted to 0 or 1 without errors like '1', 0x00, b'1' or TRUE/FALSE.

If you don't want to permit NULLs, add the NOT NULL option

bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))

Note that there is virtually no difference if you use TINYINT, TINYINT(1) or TINYINT(123).

If you want your schema to be upwards compatible, you can also use BOOL or BOOLEAN

bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))

db<>fiddle demo

How can I control the width of a label tag?

Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.

display: block; makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

Java - Search for files in a directory

This looks like a homework question, so I'll just give you a few pointers:

Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

You're not using Scanner for anything, and it's not needed here, get rid of it.

Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

Using comma as list separator with AngularJS

I like simbu's approach, but I ain't comfortable to use first-child or last-child. Instead I only modify the content of a repeating list-comma class.

.list-comma + .list-comma::before {
    content: ', ';
}
<span class="list-comma" ng-repeat="destination in destinations">
    {{destination.name}}
</span>

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

Target:
class=collapse //I can collapse
id=myDiv

This is same for other type of toggle actions like tab, modal, dropdown

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

Node.js Port 3000 already in use but it actually isn't?

For windows, The Task Manager would definitely show a node process running. Try to kill the process, it will solve the problem.

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

PHP - iterate on string characters

For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

$string = "a sample string for testing";
$char = $string[4] // equals to m

I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):

$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m

This method is going to be faster cause we are using a real array and not assuming one to be an array.

Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

Using string[i]
0.24960017204285 Seconds

Using str_split
0.18720006942749 Seconds

Which means the second method is way faster.

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

Generate Controller and Model

Thank you @user1909426, I can found solution by php artisan list it will list all command that was used on L4. It can create controller only not Model. I follow this command to generate controller.

php artisan controller:make [Name]Controller

On Laravel 5, the command has changed:

php artisan make:controller [Name]Controller

Note: [Name] name of controller

Python - Extracting and Saving Video Frames

This is Function which will convert most of the video formats to number of frames there are in the video. It works on Python3 with OpenCV 3+

import cv2
import time
import os

def video_to_frames(input_loc, output_loc):
    """Function to extract frames from input video file
    and save them as separate frames in an output directory.
    Args:
        input_loc: Input video file.
        output_loc: Output directory to save the frames.
    Returns:
        None
    """
    try:
        os.mkdir(output_loc)
    except OSError:
        pass
    # Log the time
    time_start = time.time()
    # Start capturing the feed
    cap = cv2.VideoCapture(input_loc)
    # Find the number of frames
    video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print ("Number of frames: ", video_length)
    count = 0
    print ("Converting video..\n")
    # Start converting the video
    while cap.isOpened():
        # Extract the frame
        ret, frame = cap.read()
        # Write the results back to output location.
        cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
        count = count + 1
        # If there are no more frames left
        if (count > (video_length-1)):
            # Log the time again
            time_end = time.time()
            # Release the feed
            cap.release()
            # Print stats
            print ("Done extracting frames.\n%d frames extracted" % count)
            print ("It took %d seconds forconversion." % (time_end-time_start))
            break

if __name__=="__main__":

    input_loc = '/path/to/video/00009.MTS'
    output_loc = '/path/to/output/frames/'
    video_to_frames(input_loc, output_loc)

It supports .mts and normal files like .mp4 and .avi. Tried and Tested on .mts files. Works like a Charm.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

Really annoying that RN doesn't have some sort of Tabindex system.

A functional component, for my use case, I have an array of string IDs for inputs which I iterate through and show one text input each. The following code will automatically jump the user through all of them, stopping the keyboard from disappearing/reappearing between fields and dismissing it at the end, also showing the appropriate "action" button on the keyboard.

Typescript, Native Base.

_x000D_
_x000D_
const stringFieldIDs = [
  'q1', 'q2', 'q3'
];

export default () => {
  const stringFieldRefs = stringFieldIDs.map(() => useRef < any > ());

  const basicStringField = (id: string, ind: number) => {
    const posInd = stringFieldIDs.indexOf(id);
    const isLast = posInd === stringFieldIDs.length - 1;

    return ( <
      Input blurOnSubmit = {
        isLast
      }
      ref = {
        stringFieldRefs[posInd]
      }
      returnKeyType = {
        isLast ? 'done' : 'next'
      }
      onSubmitEditing = {
        isLast ?
        undefined :
          () => stringFieldRefs[posInd + 1].current._root.focus()
      }
      />
    );
  };

  return stringFieldIDs.map(basicStringField);
};
_x000D_
_x000D_
_x000D_

Salt and hash a password in Python

Based on the other answers to this question, I've implemented a new approach using bcrypt.

Why use bcrypt

If I understand correctly, the argument to use bcrypt over SHA512 is that bcrypt is designed to be slow. bcrypt also has an option to adjust how slow you want it to be when generating the hashed password for the first time:

# The '12' is the number that dictates the 'slowness'
bcrypt.hashpw(password, bcrypt.gensalt( 12 ))

Slow is desirable because if a malicious party gets their hands on the table containing hashed passwords, then it is much more difficult to brute force them.

Implementation

def get_hashed_password(plain_text_password):
    # Hash a password for the first time
    #   (Using bcrypt, the salt is saved into the hash itself)
    return bcrypt.hashpw(plain_text_password, bcrypt.gensalt())

def check_password(plain_text_password, hashed_password):
    # Check hashed password. Using bcrypt, the salt is saved into the hash itself
    return bcrypt.checkpw(plain_text_password, hashed_password)

Notes

I was able to install the library pretty easily in a linux system using:

pip install py-bcrypt

However, I had more trouble installing it on my windows systems. It appears to need a patch. See this Stack Overflow question: py-bcrypt installing on win 7 64bit python

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

Connect multiple devices to one device via Bluetooth

I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.

Use chrome as browser in C#?

1/3/2017 --> January the 3rd 2017

Hi there, today I found this article to achieve this, the article is called "Creating an HTML UI for Desktop .NET Applications" and is intended to embed a chromium based control in a WPF application. It saved me the day.

https://www.infoq.com/articles/html-desktop-net

I hope it helps somebody else.

NOTE: it is based on DotNetBrowser, see license agreement here: https://www.teamdev.com/dotnetbrowser-licence-agreement

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

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).

Access to file download dialog in Firefox

In addition you can add

      profile.setPreference("browser.download.panel.shown",false);

To remove the downloaded file list that gets shown by default and covers up part of the web page.

My total settings are:

        DesiredCapabilities dc = DesiredCapabilities.firefox();
        dc.merge(capabillities);
        FirefoxProfile profile = new FirefoxProfile();
        profile.setAcceptUntrustedCertificates(true);
        profile.setPreference("browser.download.folderList", 4);
        profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
        profile.setPreference("browser.download.manager.showWhenStarting", false);
        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.download.useDownloadDir", true);
        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.download.manager.closeWhenDone", true);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.panel.shown",false);
        dc.setCapability(FirefoxDriver.PROFILE, profile);
        this.driver = new FirefoxDriver(dc);

Dynamically updating plot in matplotlib

Here is a way which allows to remove points after a certain number of points plotted:

import matplotlib.pyplot as plt
# generate axes object
ax = plt.axes()

# set limits
plt.xlim(0,10) 
plt.ylim(0,10)

for i in range(10):        
     # add something to axes    
     ax.scatter([i], [i]) 
     ax.plot([i], [i+1], 'rx')

     # draw the plot
     plt.draw() 
     plt.pause(0.01) #is necessary for the plot to update for some reason

     # start removing points if you don't want all shown
     if i>2:
         ax.lines[0].remove()
         ax.collections[0].remove()

Make selected block of text uppercase

Highlight the text you want to uppercase. Then hit CTRL+SHIFT+P to bring up the command palette. Then start typing the word "uppercase", and you'll see the Transform to Uppercase command. Click that and it will make your text uppercase.

Whenever you want to do something in VS Code and don't know how, it's a good idea to bring up the command palette with CTRL+SHIFT+P, and try typing in a keyword for you want. Oftentimes the command will show up there so you don't have to go searching the net for how to do something.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

Make sure the package version is equal across the solution. I just downgraded & upgraded Microsoft.AspNet.Mvc package across the solution and the problem solved.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How to get the seconds since epoch from the time + date output of gmtime()?

Note that time.gmtime maps timestamp 0 to 1970-1-1 00:00:00.

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

The inverse of time.gmtime is calendar.timegm:

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

Get single listView SelectedItem

This works for single as well as multi selection list:

foreach (ListViewItem item in listView1.SelectedItems)
{
    int index = ListViewItem.Index;
    //index is now zero based index of selected item
}

Java: Retrieving an element from a HashSet

It sounds like you're essentially trying to use the hash code as a key in a map (which is what HashSets do behind the scenes). You could just do it explicitly, by declaring HashMap<Integer, MyHashObject>.

There is no get for HashSets because typically the object you would supply to the get method as a parameter is the same object you would get back.

What is the difference between `let` and `var` in swift?

It's maybe better to state this difference by the Mutability / Immutability notion that is the correct paradigm of values and instances changeability in Objects space which is larger than the only "constant / variable" usual notions. And furthermore this is closer to Objective C approach.

2 data types: value type and reference type.

In the context of Value Types:

'let' defines a constant value (immutable). 'var' defines a changeable value (mutable).

let aInt = 1   //< aInt is not changeable

var aInt = 1   //< aInt can be changed

In the context of Reference Types:

The label of a data is not the value but the reference to a value.

if aPerson = Person(name:Foo, first:Bar)

aPerson doesn't contain the Data of this person but the reference to the data of this Person.

let aPerson = Person(name:Foo, first:Bar)
               //< data of aPerson are changeable, not the reference

var aPerson = Person(name:Foo, first:Bar)
               //< both reference and data are changeable.

eg:

var aPersonA = Person(name:A, first: a)
var aPersonB = Person(name:B, first: b)

aPersonA = aPersonB

aPersonA now refers to Person(name:B, first: b)

and

let aPersonA = Person(name:A, first: a)
let aPersonB = Person(name:B, first: b)

let aPersonA = aPersonB // won't compile

but

let aPersonA = Person(name:A, first: a)

aPersonA.name = "B" // will compile

Writing to a TextBox from another thread?

On your MainForm make a function to set the textbox the checks the InvokeRequired

public void AppendTextBox(string value)
{
    if (InvokeRequired)
    {
        this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
        return;
    }
    ActiveForm.Text += value;
}

although in your static method you can't just call.

WindowsFormsApplication1.Form1.AppendTextBox("hi. ");

you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call

AppendTextBox("hi. ");

It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.

Full Sample

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        new Thread(SampleFunction).Start();
    }

    public void AppendTextBox(string value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
            return;
        }
        textBox1.Text += value;
    }

    void SampleFunction()
    {
        // Gets executed on a seperate thread and 
        // doesn't block the UI while sleeping
        for(int i = 0; i<5; i++)
        {
            AppendTextBox("hi.  ");
            Thread.Sleep(1000);
        }
    }
}

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Aus_lacy's post gave me the idea of trying related methods, of which join does work:

In [196]:

hl.name = 'hl'
Out[196]:
'hl'
In [199]:

df.join(hl).head(4)
Out[199]:
high    low loc_h   loc_l   hl
2014-01-01 17:00:00 1.376235    1.375945    1.376235    1.375945    1.376090
2014-01-01 17:01:00 1.376005    1.375775    NaN NaN NaN
2014-01-01 17:02:00 1.375795    1.375445    NaN 1.375445    1.375445
2014-01-01 17:03:00 1.375625    1.375515    NaN NaN NaN

Some insight into why concat works on the example but not this data would be nice though!

Get element from within an iFrame

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

You could more simply write:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

and the first valid inner doc will be returned.

Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById...etc.)

IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

Remove Duplicate objects from JSON Array

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];          

 function uniqurArray(array){
                         var a = array.concat();
                        for(var i=0; i<a.length; i++) {
                            for(var j=i+1; j<a.length; j++) {
                                if(a[i].Grade === a[j].Grade){
                                    a.splice(j--, 1);
                                }
                            }
                        }

                        return a;
                    }

    uniqurArray(standardsList) // put this js in console and you get uniq object in array

Difference Between Select and SelectMany

The SelectMany() method is used to flatten a sequence in which each of the elements of the sequence is a separate.

I have class user same like this

class User
    {
        public string UserName { get; set; }
        public List<string> Roles { get; set; }
    }

main:

var users = new List<User>
            {
                new User { UserName = "Reza" , Roles = new List<string>{"Superadmin" } },
                new User { UserName = "Amin" , Roles = new List<string>{"Guest","Reseption" } },
                new User { UserName = "Nima" , Roles = new List<string>{"Nurse","Guest" } },
            };

var query = users.SelectMany(user => user.Roles, (user, role) => new { user.UserName, role });

foreach (var obj in query)
{
    Console.WriteLine(obj);
}
//output

//{ UserName = Reza, role = Superadmin }
//{ UserName = Amin, role = Guest }
//{ UserName = Amin, role = Reseption }
//{ UserName = Nima, role = Nurse }
//{ UserName = Nima, role = Guest }

You can use operations on any item of sequence

int[][] numbers = {
                new[] {1, 2, 3},
                new[] {4},
                new[] {5, 6 , 6 , 2 , 7, 8},
                new[] {12, 14}
            };

IEnumerable<int> result = numbers
                .SelectMany(array => array.Distinct())
                .OrderBy(x => x);

//output

//{ 1, 2 , 2 , 3, 4, 5, 6, 7, 8, 12, 14 }
 List<List<int>> numbers = new List<List<int>> {
                new List<int> {1, 2, 3},
                new List<int> {12},
                new List<int> {5, 6, 5, 7},
                new List<int> {10, 10, 10, 12}
            };

 IEnumerable<int> result = numbers
                .SelectMany(list => list)
                .Distinct()
                .OrderBy(x=>x);

//output

// { 1, 2, 3, 5, 6, 7, 10, 12 }

Causes of getting a java.lang.VerifyError

Another reason for this error can be the combination of AspectJ <= 1.6.11 with JRE > 6.

See Eclipse Bug 353467 and Kieker ticket 307 for details.

This is especially true when everything works fine on JRE 6 and moving to JRE7 breaks things.

Nested jQuery.each() - continue/break

Labeled Break

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}

How to keep two folders automatically synchronized?

You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:

It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.

But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!

I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.

How to hide form code from view code/inspect element browser?

if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

Can't ping a local VM from the host

Try dropping all the firewall, the one from your VM and the one from you Laptop, or add the rule in your firewall where you can ping

How to scroll to specific item using jQuery?

You can scroll by jQuery and JavaScript Just need two element jQuery and this JavaScript code :

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to-id").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 1500);
  });
});

_x000D_
_x000D_
$(function() {_x000D_
  // Generic selector to be used anywhere_x000D_
  $(".js-scroll-to-id").click(function(e) {_x000D_
_x000D_
    // Get the href dynamically_x000D_
    var destination = $(this).attr('href');_x000D_
_x000D_
    // Prevent href=“#” link from changing the URL hash (optional)_x000D_
    e.preventDefault();_x000D_
_x000D_
    // Animate scroll to destination_x000D_
    $('html, body').animate({_x000D_
      scrollTop: $(destination).offset().top_x000D_
    }, 1500);_x000D_
  });_x000D_
});
_x000D_
#pane1 {_x000D_
  background: #000;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}_x000D_
_x000D_
#pane2 {_x000D_
  background: #ff0000;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}_x000D_
_x000D_
#pane3 {_x000D_
  background: #ccc;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul class="nav">_x000D_
  <li>_x000D_
    <a href="#pane1" class=" js-scroll-to-id">Item 1</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane3" class=" js-scroll-to-id">Item 3</a>_x000D_
  </li>_x000D_
</ul>_x000D_
<div id="pane1"></div>_x000D_
<div id="pane2"></div>_x000D_
<div id="pane3"></div>_x000D_
<!-- example of a fixed nav menu -->_x000D_
<ul class="nav">_x000D_
  <li>_x000D_
    <a href="#pane3" class="js-scroll-to-id">Item 1</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane1" class="js-scroll-to-id">Item 3</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

What are the performance characteristics of sqlite with very large database files?

I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.

According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

This Kotlin state machine library has PlantUML export feature, it is not integrated with Android Studio but it is easy to visualize state machine structure on PlantUML web site.

https://github.com/nsk90/kstatemachine

git push rejected: error: failed to push some refs

git push -f if you have permission, but that will screw up anyone else who pulls from that repo, so be careful.

If that is denied, and you have access to the server, as canzar says below, you can allow this on the server with

git config receive.denyNonFastForwards false

getting JRE system library unbound error in build path

This is like user3076252's answer, but you'll be choosing a different set of options:

  • Project > Properties > Java Build Path
  • Select Libraries tab > Alternate JRE > Installed JREs...
  • Click "Search." Unless you know the exact folder name, you should choose a drive to search.

It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.

Simple way to convert datarow array to datatable

You could use System.Linq like this:

if (dataRows != null && dataRows.Length > 0)
{
   dataTable = dataRows.AsEnumerable().CopyToDataTable();
}

How to display a jpg file in Python?

Don't forget to include

import Image

In order to show it use this :

Image.open('pathToFile').show()

Expression must have class type

Summary: Instead of a.f(); it should be a->f();

In main you have defined a as a pointer to object of A, so you can access functions using the -> operator.

An alternate, but less readable way is (*a).f()

a.f() could have been used to access f(), if a was declared as: A a;

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

keep using the id


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserVerification extends Model
{
    protected $table = 'user_verification';
    protected $fillable =   [
                            'id',
                            'email',
                            'verification_token'
                            ];
    //$timestamps = false;
    protected $primaryKey = 'verification_token';
}

and get the email :

$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);

Check if date is a valid one

Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

It is badDate coming from your picker in this example

https://jsfiddle.net/xs8tvox9/

var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";

var splittedDate = badDate.split('-');

if (splittedDate.length == 3) {
  var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
  alert(d.isValid())
} else {
  //incorrectFormat
}

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

jquery disable form submit on enter

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.

<script type="text/javascript">
        function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
        }

        document.onkeypress = stopRKey;
</script> 

How to reverse a singly linked list using only two pointers?

To swap two variables without the use of a temporary variable,

a = a xor b
b = a xor b
a = a xor b

fastest way is to write it in one line

a = a ^ b ^ (b=a)

Similarly,

using two swaps

swap(a,b)
swap(b,c)

solution using xor

a = a^b^c
b = a^b^c
c = a^b^c
a = a^b^c

solution in one line

c = a ^ b ^ c ^ (a=b) ^ (b=c)
b = a ^ b ^ c ^ (c=a) ^ (a=b)
a = a ^ b ^ c ^ (b=c) ^ (c=a)

The same logic is used to reverse a linked list.

typedef struct List
{
 int info;
 struct List *next;
}List;


List* reverseList(List *head)
{
 p=head;
 q=p->next;
 p->next=NULL;
 while(q)
 {
    q = (List*) ((int)p ^ (int)q ^ (int)q->next ^ (int)(q->next=p) ^ (int)(p=q));
 }
 head = p;
 return head;
}  

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}