Programs & Examples On #File association

A file association associates a file with an application capable of opening that file. More commonly, a file association associates a class of files (usually determined by their filename extension, such as .txt) with a corresponding application.

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

How to execute Python scripts in Windows?

Simply run the command:

C:>python .\file_name.py

Assuming the file name is within same folder and Python has already been added to environment variables.

How to show x and y axes in a MATLAB graph?

By default, plot does show axes, unless you've modified some settings. Try the following

hold on; % make sure no new plot window is created on every plot command
axes(); % produce plot window with axes
plot(% whatever your plot command is);
plot([0 10], [0 0], 'k-'); % plot the horizontal line

Round to 5 (or other number) in Python

Removing the 'rest' would work:

rounded = int(val) - int(val) % 5

If the value is aready an integer:

rounded = val - val % 5

As a function:

def roundint(value, base=5):
    return int(value) - int(value) % int(base)

How to create and add users to a group in Jenkins for authentication?

According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.

However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.

How to use Morgan logger?

Morgan :- Morgan is a middleware which will help us to identify the clients who are accessing our application. Basically a logger.

To Use Morgan, We need to follow below steps :-

  1. Install the morgan using below command:

npm install --save morgan

This will add morgan to json.package file

  1. Include the morgan in your project

var morgan = require('morgan');

3> // create a write stream (in append mode)

var accessLogStream = fs.createWriteStream(
      path.join(__dirname, 'access.log'), {flags: 'a'}
 );
// setup the logger 
app.use(morgan('combined', {stream: accessLogStream}));

Note: Make sure you do not plumb above blindly make sure you have every conditions where you need .

Above will automatically create a access.log file to your root once user will access your app.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

If you're just checking before trying to add a new value, use the ContainsKey method:

if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
}

If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Regular expression to match any character being repeated more than 10 times

The regex you need is /(.)\1{9,}/.

Test:

#!perl
use warnings;
use strict;
my $regex = qr/(.)\1{9,}/;
print "NO" if "abcdefghijklmno" =~ $regex;
print "YES" if "------------------------" =~ $regex;
print "YES" if "========================" =~ $regex;

Here the \1 is called a backreference. It references what is captured by the dot . between the brackets (.) and then the {9,} asks for nine or more of the same character. Thus this matches ten or more of any single character.

Although the above test script is in Perl, this is very standard regex syntax and should work in any language. In some variants you might need to use more backslashes, e.g. Emacs would make you write \(.\)\1\{9,\} here.

If a whole string should consist of 9 or more identical characters, add anchors around the pattern:

my $regex = qr/^(.)\1{9,}$/;

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

android studio 0.4.2: Gradle project sync failed error

After reporting the problem on the Android Studio feedback site, they found a solution for me. I am now using Gradle 1.10 and Android Studio 0.4.3.

Here is the link to the page with a description of how I fixed mine: https://code.google.com/p/android/issues/detail?id=65219

Hope this helps!

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

How to perform keystroke inside powershell?

Also the $wshell = New-Object -ComObject wscript.shell; helped a script that was running in the background, it worked fine with just but adding $wshell. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")

How to make/get a multi size .ico file?

What i do is to prepare a 512x512 PNG, the Alpha Channel is good for rounded corners or drop shadows, then I upload it to this site http://convertico.com/, and for free then it returns me a 6 sizes .ico file with 256x256, 128x128, 64x64, 48x48, 32x32 and 16x16 sizes.

Passing an array of parameters to a stored procedure

You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.

CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
    DELETE YourTable
    FROM YourTable                    
    LEFT OUTER JOIN #temp T ON T.myid=s.id
    WHERE s.id IS NULL
END

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

How to set the height of table header in UITableView?

You can create a UIView with the desired height (the width should be that of the UITableView), and inside it you can place a UIImageView with the picture of the proper dimensions: they won't stretch automatically.

You can also give margin above and below the inner UIImageView, by giving a higher height to the container view.

Additionally, you can assign a Translation transform in order to place the image in the middle of its container header view, for example.

Android - Dynamically Add Views into View

// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);

// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;

for (int i = 1; i < 101; i++){
    // Add the text layout to the parent layout
    view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);

    // In order to get the view we have to use the new view with text_layout in it
    TextView textView = (TextView)view.findViewById(R.id.text);
    textView.setText("Row " + i);

    // Add the text view to the parent layout
    parentLayout.addView(textView);
}

Npm install failed with "cannot run in wd"

I fixed this by changing the ownership of /usr/local and ~/Users/user-name like so:

sudo chown -R my_name /usr/local

This allowed me to do everything without sudo

How can I see CakePHP's SQL dump in the controller?

What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

<?php echo $this->element('sql_dump');?>

It is also depending on debug variable setted into Config/core.php

How to send an email from JavaScript

If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

Deleting an element from an array in PHP

I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):

class obj {
    protected $fields = array('field1','field2');
    protected $field1 = array();
    protected $field2 = array();
    protected loadfields(){}
    // This will load the $field1 and $field2 with rows of data for the column they describe
    protected function clearFields($num){
        foreach($fields as $field) {
            unset($this->$field[$num]);
            // This did not work the line below worked
            unset($this->{$field}[$num]); // You have to resolve $field first using {}
        }
    }
}

The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.

Remove empty elements from an array in Javascript

What about this(ES6) : To remove Falsy value from an array.

var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];

arr.filter((v) => (!!(v)==true));

//output:

//[1, 2, "test", "false", true, 3, 4, 5, "end"]

HTML - how to make an entire DIV a hyperlink?

Why don't you just do this

<a href="yoururl.html"><div>...</div></a>

That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

How to use an arraylist as a prepared statement parameter

If you have ArrayList then convert into Array[Object]

ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt = 
            conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Pandas groupby: How to get a union of strings

You can use the apply method to apply an arbitrary function to the grouped data. So if you want a set, apply set. If you want a list, apply list.

>>> d
   A       B
0  1    This
1  2      is
2  3       a
3  4  random
4  1  string
5  2       !
>>> d.groupby('A')['B'].apply(list)
A
1    [This, string]
2           [is, !]
3               [a]
4          [random]
dtype: object

If you want something else, just write a function that does what you want and then apply that.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

When I ran into this error, I spent hours trying to find a solution.

My issue was that when I went to save the file I had accidentally hit the key stroke "G" in the web.config. I had a straggler Character just sittings outside, so the web.config did not know how to interpret the improperly formatted data.

Hope this helps.

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

adb uninstall <package_name>

can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:

  1. In Android Studio, click the drop down list to the left of Run button, and select Edit configurations...
  2. Click on app under Android Application, and in General Tab, find the heading 'Before Launch'
  3. Click the + button, select Run external tool, click the + button in the popup window.
  4. Give some name (Eg adb uninstall) and description, and type adb in Program: and uninstall <your-package-name> in Parameters:. Make sure that the new item is selected when you click Ok in the popup window.

Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

Android ImageView's onClickListener does not work

can you Try this and tell me what happens ?? :

JAVA :

ImageView imgFavorite = (ImageView) findViewById(R.id.favorite_icon);
imgFavorite.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(YourActivityName.this,
                "The favorite list would appear on clicking this icon",
                Toast.LENGTH_LONG).show();
    }
});

or you should add this :

imgFavorite.setClickable(true); 

KOTLIN :

imgFavorite.setOnClickListener { view ->
    Toast.makeText(this@YourActivityName, R.string.toast_favorite_list_would_appear, Toast.LENGTH_LONG).show()
}
// either you make your imageView clickable programmatically
imgFavorite.clickable = true

// or via xml on your layout file
<ImageView .... android:clickable="true" />

ERROR 1049 (42000): Unknown database

Very simple solution. Just rename your database and configure your new database name in your project.

The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.

phpmyadmin -> operations -> Rename database to

How do I get the value of a registry key and ONLY the value using powershell

Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';

Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
    $command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
    $value = Invoke-Expression -Command $command;
    $_ + ' : ' + $value; };

Like this:

DbgJITDebugLaunchSetting : 16

DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d

InstallRoot : C:\Windows\Microsoft.NET\Framework\

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

LINQ syntax where string value is not null or empty

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

What are some good Python ORM solutions?

We use Elixir alongside SQLAlchemy and have liked it so far. Elixir puts a layer on top of SQLAlchemy that makes it look more like the "ActiveRecord pattern" counter parts.

array of string with unknown size

I suppose that the array size if a computed value.

int size = ComputeArraySize();

// Then

String[] array = new String[size]; 

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

In pom.xml file we need to add

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.8</version>
</dependency>

How do I create an average from a Ruby array?

what I don't like about the accepted solution

arr = [5, 6, 7, 8]
arr.inject{ |sum, el| sum + el }.to_f / arr.size
=> 6.5

is that it does not really work in a purely functional way. we need a variable arr to compute arr.size at the end.

to solve this purely functionally we need to keep track of two values: the sum of all elements, and the number of elements.

[5, 6, 7, 8].inject([0.0,0]) do |r,ele|
    [ r[0]+ele, r[1]+1 ]
end.inject(:/)
=> 6.5   

Santhosh improved on this solution: instead of the argument r being an array, we could use destructuring to immediatly pick it apart into two variables

[5, 6, 7, 8].inject([0.0,0]) do |(sum, size), ele| 
   [ sum + ele, size + 1 ]
end.inject(:/)

if you want to see how it works, add some puts:

[5, 6, 7, 8].inject([0.0,0]) do |(sum, size), ele| 
   r2 = [ sum + ele, size + 1 ]
   puts "adding #{ele} gives #{r2}"
   r2
end.inject(:/)

adding 5 gives [5.0, 1]
adding 6 gives [11.0, 2]
adding 7 gives [18.0, 3]
adding 8 gives [26.0, 4]
=> 6.5

We could also use a struct instead of an array to contain the sum and the count, but then we have to declare the struct first:

R=Struct.new(:sum, :count)
[5, 6, 7, 8].inject( R.new(0.0, 0) ) do |r,ele|
    r.sum += ele
    r.count += 1
    r
end.inject(:/)

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/

https://www.mssqltips.com/sqlservertip/1336/pass-parameters-and-options-with-a-url-in-sql-reporting-services/

How do check if a PHP session is empty?

if(isset($_SESSION))
{}
else
{}

How to send objects through bundle

One More way to send objects through bundle is by using bundle.putByteArray
Sample code

public class DataBean implements Serializable {
private Date currentTime;

public setDate() {
    currentTime = Calendar.getInstance().getTime();
 }

public Date getCurrentTime() {
    return currentTime;
 }
}

put Object of DataBean in to Bundle:

class FirstClass{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//When you want to start new Activity...
Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
            Bundle dataBundle=new Bundle();
            DataBean dataObj=new DataBean();
            dataObj.setDate();
            try {
                dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

            dataIntent.putExtras(dataBundle);

            startActivity(dataIntent);
}

Converting objects to byte arrays

/**
 * Converting objects to byte arrays
 */
static public byte[] object2Bytes( Object o ) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream( baos );
      oos.writeObject( o );
      return baos.toByteArray();
    }

Get Object back from Bundle:

class SecondClass{
DataBean dataBean;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//Get Info from Bundle...
    Bundle infoBundle=getIntent().getExtras();
    try {
        dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Method to get objects from byte arrays:

/**
 * Converting byte arrays to objects
 */
static public Object bytes2Object( byte raw[] )
        throws IOException, ClassNotFoundException {
      ByteArrayInputStream bais = new ByteArrayInputStream( raw );
      ObjectInputStream ois = new ObjectInputStream( bais );
      Object o = ois.readObject();
      return o;
    }

Hope this will help to other buddies.

Javascript - Append HTML to container element without innerHTML

This is what DocumentFragment was meant for.

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes

In LINQ, select all values of property X where X != null

This is adapted from CodesInChaos's extension method. The name is shorter (NotNull) and more importantly, restricts the type (T) to reference types with where T : class.

    public static IEnumerable<T> NotNull<T>(this IEnumerable<T> source) where T : class
    {
        return source.Where(item => item != null);
    }

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.

Send file via cURL from form POST in PHP

cURL file object in procedural method:

$file = curl_file_create('full path/filename','extension','filename');

cURL file object in Oop method:

$file = new CURLFile('full path/filename','extension','filename');

$post= array('file' => $file);

$curl = curl_init();  
//curl_setopt ... 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Drag and drop elements from list into separate blocks

I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.

Markup-

<div class="row">
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 1</h1>
        </div>
        <div id="container1" class="panel-body box-container">
          <div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
          <div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
          <div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
          <div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
          <div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
        </div>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 2</h1>
        </div>
        <div id="container2" class="panel-body box-container"></div>
      </div>
    </div>
  </div>

JQuery codes-

$(document).ready(function() {

$('.box-item').draggable({
    cursor: 'move',
    helper: "clone"
});

$("#container1").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container1");
      }
    });
  }
});

$("#container2").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container2");
      }
    });
  }
});

});

CSS-

.box-container {
    height: 200px;
}

.box-item {
    width: 100%;
    z-index: 1000
}

Check the plunker JQuery Drag Drop

What is a loop invariant?

The meaning of invariant is never change

Here the loop invariant means "The change which happen to variable in the loop(increment or decrement) is not changing the loop condition i.e the condition is satisfying " so that the loop invariant concept has came

Differences between Emacs and Vim

There is a huge difference on a day-to-day level - Vim (or any vi variant) is inherently modal (you go into command modes where you cannot edit) and Emacs (along with most other editors) are not.

Sure, using menus and such you don't have to actually enter command mode in Vim - at first. But to use even a tiny fraction of the power of Vim you will. That is at the heart of the Vim/Emacs debate.

Personally, I also think Emacs is far more extensible. You can find Elisp packages for many things.

I am curious, though, why you are thinking to learn one of these over a more traditional IDE. What is it you want to learn one of these for?

How to run vi on docker container?

Alternatively, keep your docker images small by not installing unnecessary editors. You can edit the files over ssh from the docker host to the container:

vim scp://remoteuser@container-ip//path/to/document

How to get 2 digit year w/ Javascript?

Given a date object:

date.getFullYear().toString().substr(2,2);

It returns the number as string. If you want it as integer just wrap it inside the parseInt() function:

var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);

Example with the current year in one line:

var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));

Python Iterate Dictionary by Index

When I need to keep the order, I use a list and a companion dict:

color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
    color[i]

The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:

fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)): 
    fruitcolor[i][1]
for f, c in fruitcolor:
    c

Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.

DBMS_OUTPUT.PUT_LINE not printing

I am using Oracle SQL Developer,

In this tool, I had to enable DBMS output to view the results printed by dbms_output.put_line

You can find this option in the result pane where other query results are displayed. so, in the result pane, I have 7 tabs. 1st tab named as Results, next one is Script Output and so on. Out of this you can find a tab named as "DBMS Output" select this tab, then the 1st icon (looks like a dialogue icon) is Enable DBMS Output. Click this icon. Then you execute the PL/SQL, then select "DBMS Output tab, you should be able to see the results there.

Quick Sort Vs Merge Sort

quicksort is named so for a reason ,

highlights : both are stable sorts,(simply an implementation nuisance ) , so lets just move on to complexities

its very confusing with just the big-oh notations being spilled and "abused" , both have average case complexity of 0(nlogn) ,

but merge sort is always 0(nlogn) , whereas quicksort for bad partitions, ie skewed partitions like 1 element-10 element (which can happen due to sorted or reverse sorted list ) can lead to a 0(n^2)..

.. and so we have randomized quicksort , where we pick the pivot randomly and avoid such skewed partitioning , thereby nullifying the whole n^2 scenario anyway even for moderately skewed partitioning like 3-4 , we have a nlog(7/4)n, ideally we want 1-1 partion , thus the whole 2 of O(nlog(2)n).

so it is O(nlogn) , almost always and unlike merge sort the constants hidden under the "big-oh" notation are better for quicksort than for mergesort ..and it doesnt use up extra space like merge sort.

but getting quicksort run perfectly requires tweaking ,rephrase , quicksort provides you opportunities to tweak ....

Determine the number of NA values in a column

I read a csv file from local directory. Following code works for me.

# to get number of which contains na
sum(is.na(df[, c(columnName)]) # to get number of na row

# to get number of which not contains na
sum(!is.na(df[, c(columnName)]) 

#here columnName is your desire column name

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

where does MySQL store database files?

Check your my.cnf file in your MySQL program directory, look for

[mysqld]
datadir=

The datadir is the location where your MySQL database is stored.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Add these two lines to your build.gradle in the android section:

android{
    compileOptions {
            sourceCompatibility 1.8
            targetCompatibility 1.8
        }
}

How to select an item in a ListView programmatically?

if (listView1.Items.Count > 0)
{
    listView1.FocusedItem = listView1.Items[0];
    listView1.Items[0].Selected = true;
    listView1.Select();
}

Invalid self signed SSL cert - "Subject Alternative Name Missing"

To fix this, you need to supply an extra parameter to openssl when you're creating the cert, basically

-sha256 -extfile v3.ext

where v3.ext is a file like so, with %%DOMAIN%% replaced with the same name you use as your Common Name. More info here and over here. Note that typically you'd set the Common Name and %%DOMAIN%% to the domain you're trying to generate a cert for. So if it was www.mysupersite.com, then you'd use that for both.

v3.ext

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%

Note: Scripts that address this issue, and create fully trusted ssl certs for use in Chrome, Safari and from Java clients can be found here

Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I am adding few more understanding.

  1. Cursor is only about a statement objecct; It is neither resultSet nor the connection object.
  2. But still we have to close the resultset to free some oracle memory. Still if you don't close the resultset that won't be counted for CURSORS.
  3. Closing Statement object will automatically close resultset object too.
  4. Cursor will be created for all the SELECT/INSERT/UPDATE/DELETE statement.
  5. Each ORACLE DB instance can be identified using oracle SID; similarly ORACLE DB can identify each connection using connection SID. Both SID are different.
  6. So ORACLE session is nothing but a jdbc(tcp) connection; which is nothing but one SID.
  7. If we set maximum cursors as 500 then it is only for one JDBC session/connection/SID.
  8. So we can have many JDBC connection with its respective no of cursors (statements).
  9. Once the JVM is terminated all the connections/cursors will be closed, OR JDBCConnection is closed CURSORS with respect to that connection will be closed.

Loggin as sysdba.

In Putty (Oracle login):

  [oracle@db01 ~]$ sqlplus / as sysdba

In SqlPlus:

UserName: sys as sysdba

Set session_cached_cursors value to 0 so that it wont have closed cursors.

 alter session set session_cached_cursors=0
 select * from V$PARAMETER where name='session_cached_cursors'

Select existing OPEN_CURSORS valuse set per connection in DB

 SELECT max(a.value) as highest_open_cur, p.value as max_open_cur FROM v$sesstat a, v$statname b, v$parameter p WHERE a.statistic# = b.statistic# AND b.name = 'opened cursors current' AND p.name= 'open_cursors'  GROUP BY p.value;

Below is the query to find the SID/connections list with open cursor values.

 SELECT a.value, s.username, s.sid, s.serial#
 FROM v$sesstat a, v$statname b, v$session s
 WHERE a.statistic# = b.statistic#  AND s.sid=a.sid 
 AND b.name = 'opened cursors current' AND username = 'SCHEMA_NAME_IN_CAPS'

Use the below query to identify the sql's in the open cursors

 SELECT oc.sql_text, s.sid 
 FROM v$open_cursor oc, v$session s
 WHERE OC.sid = S.sid
 AND s.sid=1604
 AND OC.USER_NAME ='SCHEMA_NAME_IN_CAPS'

Now debug the Code and Enjoy!!! :)

Setting Margin Properties in code

Margin is returning a struct, which means that you are editing a copy. You will need something like:

var margin = MyControl.Margin;
margin.Left = 10;
MyControl.Margin = margin;

How can you find out which process is listening on a TCP or UDP port on Windows?

You can get more information if you run the following command:

netstat -aon | find /i "listening" |find "port"

using the 'Find' command allows you to filter the results. find /i "listening" will display only ports that are 'Listening'. Note, you need the /i to ignore case, otherwise you would type find "LISTENING". | find "port" will limit the results to only those containing the specific port number. Note, on this it will also filter in results that have the port number anywhere in the response string.

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to set UTF-8 encoding for a PHP file

PHP, by default, always returns the following header: "Content-Type: text/html" (notice no charset), therefore you must use

<?php header('Content-type: text/plain; charset=utf-8'); ?>

set option "selected" attribute from dynamic created option

So many wrong answers!

To specify the value that a form field should revert to upon resetting the form, use the following properties:

  • Checkbox or radio button: defaultChecked
  • Any other <input> control: defaultValue
  • Option in a drop down list: defaultSelected

So, to specify the currently selected option as the default:

var country = document.getElementById("country");
country.options[country.selectedIndex].defaultSelected = true;

It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:

var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
    country.options[i].defaultSelected = i == country.selectedIndex;
}

Now, when the form is reset, the selected option will be the one you specified.

Print array elements on separate lines in Bash?

Just quote the argument to echo:

( IFS=$'\n'; echo "${my_array[*]}" )

the sub shell helps restoring the IFS after use

Howto? Parameters and LIKE statement SQL

Well, I'd go with:

 Dim cmd as New SqlCommand(
 "SELECT * FROM compliance_corner"_
  + " WHERE (body LIKE @query )"_ 
  + " OR (title LIKE @query)")

 cmd.Parameters.Add("@query", "%" +searchString +"%")

Commenting code in Notepad++

This link was exactly what I was searching for .

Let me summarize the answers for others' benefit (for python and notepad++)

1) Ctrl+K on multiple lines (i.e. selected region) allows you to block comment.

Also note that pressing the combination multiple times allows you to add multiple "#"s (sometimes I use that while testing to differentiate from other comments)

2) Ctrl+Shift+K (on the commented region) allows you to perform block uncomment

3) Ctrl+Shift+K on an uncommented selected region does not comment it

4) Ctrl+Q allows you to block comment/uncomment in a toggled mode (meaning, you cannot add multiple '#'s like in 1) )

Hope this helps another wandering soul.

Question - how would you develop a hack of keyboard combinations to comment/uncomment if there were no shortcuts? Just curious. I've no clue hence asking.

How to add smooth scrolling to Bootstrap's scroll spy function

Do you really need that plugin? You can just animate the scrollTop property:

$("#nav ul li a[href^='#']").on('click', function(e) {

   // prevent default anchor click behavior
   e.preventDefault();

   // store hash
   var hash = this.hash;

   // animate
   $('html, body').animate({
       scrollTop: $(hash).offset().top
     }, 300, function(){

       // when done, add hash to url
       // (default click behaviour)
       window.location.hash = hash;
     });

});

fiddle

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

How to write console output to a txt file

There is no need to write any code, just in cmd on the console you can write:

javac myFile.java
java ClassName > a.txt

The output data is stored in the a.txt file.

Increase bootstrap dropdown menu width

Usually the desire is to match the menu width to the width of the dropdown parent. This can be achieved easily like so:

.dropdown-menu {
  width:100%;
}

How do you round a number to two decimal places in C#?

One thing you may want to check is the Rounding Mechanism of Math.Round:

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

Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

How to install both Python 2.x and Python 3.x in Windows

What I have done on my own windows computer where I have Python 2.7 and Python 3.4 installed is I wrote a simple .bat file in the same directory as my Python.exe files. They look something like,

cmd /k "c:\python27\python.exe" %*

The %* allows you to add arguments (Python files) afterwards. I believe /k keeps the prompt open after it finishes running the script. Then I save that as python27.bat Then I go to my Python 3 directory and make a bat file there. Now in my command line I can write

Python27 helloworld.py

Or

Python34 helloworld.py

And they will run in their respective versions of Python. Make sure that c:\python27 and c:\python34 are in your environment variables.

I got my answer from here

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

How to schedule a periodic task in Java?

If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.

background-image: url("images/plaid.jpg") no-repeat; wont show up

You may debug using two ways:

  1. Press CTRL+U to view page Source . Press CTRL+F to find "mystyles.css" in source . click on mystyles.css link and check if it is not showing "404 not found".

  2. You can INSPECT ELEMENT IN FIRBUG and set path to Image ,Set Image height and width because sometimes image doesnt show up.

Hope this may works !!.

What is the difference between <html lang="en"> and <html lang="en-US">?

RFC 3066 gives the details of the allowed values (emphasis and links added):

All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.

I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:

Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.

By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.

A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse):

Type: variant

Subtag: scouse

Description: Scouse

Added: 2006-09-18

Prefix: en

Comments: English Liverpudlian dialect known as 'Scouse'

There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad (17th century French).


The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:

Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.

I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

UIView Hide/Show with animation

UIView.transition(with: title3Label, duration: 0.4,
                          options: .transitionCrossDissolve,
                          animations: {
                            self.title3Label.isHidden = !self.title3Label.isHidden
                      })

Applying transition on View with some delay gives hide and show effect

Handling 'Sequence has no elements' Exception

First() is causing this if your select returns 0 rows. You either have to catch that exception, or use FirstOrDefault() which will return null in case of no elements.

Changing the URL in react-router v4 without using Redirect or Link

Try this,

this.props.router.push('/foo')

warning works for versions prior to v4

and

this.props.history.push('/foo')

for v4 and above

Get the row(s) which have the max value in groups using groupby

Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.

In [365]: import pandas as pd

In [366]: df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

In [367]: df                                                                                                       
Out[367]: 
   count  mt   sp  val
0      3  S1  MM1    a
1      2  S1  MM1    n
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
5      1  S4  MM2  dgb
6      2  S2  MM4   rd
7      2  S2  MM4   cb
8      7  S2  MM4  uyi


### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]                                                       
Out[368]: 
   count  mt   sp  val
0      3  S1  MM1    a
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
8      7  S2  MM4  uyi

### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values                                                        
Out[369]: array([0, 2, 3, 4, 8])

Declaring a variable and setting its value from a SELECT query in Oracle

ORA-01422: exact fetch returns more than requested number of rows

if you don't specify the exact record by using where condition, you will get the above exception

DECLARE
     ID NUMBER;
BEGIN
     select eid into id from employee where salary=26500;
     DBMS_OUTPUT.PUT_LINE(ID);
END;

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

How do I prompt a user for confirmation in bash script?

This what I found elsewhere, is there a better possible version?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
   exit
fi

How to install python-dateutil on Windows?

Looks like the setup.py uses easy_install (i.e. setuptools). Just install the setuptools package and you will be all set.

To install setuptools in Python 2.6, see the answer to this question.

How do you set the max number of characters for an EditText in Android?

Obviously you can use maxLength in xml or InputFilter.LengthFilter as answered above. But for me in some cases, it was not enough. I created a class for more flexible settings of EditText: https://github.com/devapro/NumberWatcher It is implementation only for numbers input, but you can change it for any of the types.

How do I change the root directory of an Apache server?

I was working with LAMP and to change the document root folder, I have edited the default file which is there in the /etc/apache2/sites-available folder.

If you want to do the same, just edit as follows:

DocumentRoot /home/username/new_root_folder
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/username/new_root_folder>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

After this, if you type "localhost" in the browser, it will load the /home/username/new_root_folder content.

How do I write dispatch_after GCD in Swift 3, 4, and 5?

Swift 5 and above

DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
   // code to execute                 
})

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Vertical Menu in Bootstrap

Responsive utility classes

Easiest way I can think of is to have a vertical left menu AND the collapsing Top Nav in your design and attach/use bootstraps responsive css.

Then just add classes of hidden phone, tablet etc (to suit) to your left nav and hidden desktop etc to the top nav

see: http://twitter.github.com/bootstrap/scaffolding.html#responsive

play around with that and hopefully it should be able to do what you want

Regular expression search replace in Sublime Text 2

By the way, in the question above:

For:

Hello, my name is bob

Find part:

my name is (\w)+

With replace part:

my name used to be \1

Would return:

Hello, my name used to be b

Change find part to:

my name is (\w+)

And replace will be what you expect:

Hello, my name used to be bob

While (\w)+ will match "bob", it is not the grouping you want for replacement.

T-SQL Subquery Max(Date) and Joins

Try this:

Select *,
    Price = (Select top 1 Price 
             From MyPrices 
             where PartID = mp.PartID 
             order by PriceDate desc
            )
from MyParts mp

Format output string, right alignment

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.

Setting multiple attributes for an element at once with JavaScript

You could make a helper function:

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

Call it like this:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});

Perl: function to trim string leading and trailing whitespace

For those that are using Text::CSV I found this thread and then noticed within the CSV module that you could strip it out via switch:

$csv = Text::CSV->new({allow_whitespace => 1});

The logic is backwards in that if you want to strip then you set to 1. Go figure. Hope this helps anyone.

outline on only one border

The great thing about HTML/CSS is that there's usually more than one way to achieve the same effect. Here's another solution that does what you want:

<nav id="menu1">
    <ul>
        <li><a href="#">Menu Link 1</a></li>
        <li><a href="#">Menu Link 2</a></li>
    </ul>
</nav>

nav {
    background:#666;
    margin:1em;
    padding:.5em 0;
}
nav ul {
    border-top:1px dashed #fff;
    list-style:none;
    padding:.5em;
}
nav ul li {
    display:inline-block;
}
nav ul li a {
    color:#fff;
}

http://jsfiddle.net/10basetom/uCX3G/1/

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

Listing all the folders subfolders and files in a directory using php

If you're looking for a recursive directory listing solutions and arrange them in a multidimensional array. Use below code:

<?php
/**
 * Function for recursive directory file list search as an array.
 *
 * @param mixed $dir Main Directory Path.
 *
 * @return array
 */
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[$folder] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[$folder] = $folder;
            }
        }
    }

    return $allFileLists;
}//end listFolderFiles()


$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'

?>

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

You should use backdrop static , keyboard false. and can use close button off by using jQuery or can remove from modal html. Hope this help.

 $('#MyModal').modal({ backdrop: 'static', keyboard: false });
    $('#MyModal .close').css('display','none');

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How to pass data from child component to its parent in ReactJS?

The idea is to send a callback to the child which will be called to give the data back

A complete and minimal example using functions:

App will create a Child which will compute a random number and send it back directly to the parent, which will console.log the result

const Child = ({ handleRandom }) => {
  handleRandom(Math.random())

  return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>

Font-awesome, input type 'submit'

Also possible like this

<button type="submit" class="icon-search icon-large"></button>

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

How to remove all line breaks from a string

To remove new line chars use this:

yourString.replace(/\r?\n?/g, '')

Then you can trim your string to remove leading and trailing spaces:

yourString.trim()

Rails 4: before_filter vs. before_action

It is just syntax difference, in rails app there is CRUD, and seven actions basically by name index, new, create, show, update, edit, destroy.

Rails 4 make it developer friendly to change syntax before filter to before action.

before_action call method before the actions which we declare, like

before_action :set_event, only: [:show, :update, :destroy, :edit]

set_event is a method which will call always before show, update, edit and destroy.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

NVARCHAR can store Unicode characters and takes 2 bytes per character.

MassAssignmentException in Laravel

if you have table and fields on database you can simply use this command :

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

what is the multicast doing on 224.0.0.251?

Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.

The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.

mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.

If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.

Clearing an input text field in Angular2

You can just change the reference of input value, as below

<div>
    <input type="text" placeholder="Search..." #reference>
    <button (click)="reference.value=''">Clear</button>
</div>

What is Dispatcher Servlet in Spring?

The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.

I might have

  • a file /WEB-INF/jsp/pages/Home.jsp
  • and a method on a class

    @RequestMapping(value="/pages/Home.html")
    private ModelMap buildHome() {
        return somestuff;
    }
    

The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.

How it accomplishes this varies widely with configuration and Spring version.

There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.

How can I use Guzzle to send a POST request in JSON?

I use the following code that works very reliably.

The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.

The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.

If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.

    public function callAPI($request, $searchType) {
    $guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);

    try {
        $result = $guzzleClient->post( $searchType, ["json" => $request]);
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error .= '<pre>'.print_r($request, $return=true).'</pre>';
        $error .= 'No returnable data';
        Event::logError(__LINE__, __FILE__, $error);
        return false;
    }
    return json_decode($result->getBody(), $return=true);
}

Use mysql_fetch_array() with foreach() instead of while()

There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

$result_list = array();
while($row = mysql_fetch_array($result_select)) {
   result_list[] = $row;
}

foreach($result_list as $row) {
   ...
}

But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

React: Expected an assignment or function call and instead saw an expression

You use a function component:

const def = (props) => {
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>

};

In the function component, you have to write a return or just add parentheses. After the added return or parentheses your code should look like this:

const def = (props) => ({
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>
});

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

Set colspan dynamically with jquery

You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:

refToCellToRemove.remove();
refTocellToExpand.colspan = 4;

Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.

Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.

How to display a list of images in a ListView in Android?

We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.

public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 LayoutInflater inflater = (LayoutInflater) context
 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View single_row = inflater.inflate(R.layout.list_row, null,
 true);
 TextView textView = (TextView) single_row.findViewById(R.id.textView);
 ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
 textView.setText(color_names[position]);
 imageView.setImageResource(image_id[position]);
 return single_row; 
 }

Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.

Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

iOS Detection of Screenshot?

Looks like there are no direct way to do this to detect if user has tapped on home + power button. As per this, it was possible earlier by using darwin notification, but it doesn't work any more. Since snapchat is already doing it, my guess is that they are checking the iPhone photo album to detect if there is a new picture got added in between this 10 seconds, and in someway they are comparing with the current image displayed. May be some image processing is done for this comparison. Just a thought, probably you can try to expand this to make it work. Check this for more details.

Edit:

Looks like they might be detecting the UITouch cancel event(Screen capture cancels touches) and showing this error message to the user as per this blog: How to detect screenshots on iOS (like SnapChat)

In that case you can use – touchesCancelled:withEvent: method to sense the UITouch cancellation to detect this. You can remove the image in this delegate method and show an appropriate alert to the user.

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];

    NSLog(@"Touches cancelled");

    [self.imageView removeFromSuperView]; //and show an alert to the user
}

Vertically aligning CSS :before and :after content

I think a cleaner approach is to inherit the vertical alignment:

In html:

<div class="shortcut"><a href="#">Download</a></div>

And in css:

.shortcut {
    vertical-align: middle;
}
.shortcut > a:after {
    vertical-align: inherit;
{

This way the icon will align properly in any resolution/font-size combination. Great for use with icon fonts.

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

SQL Server Linked Server Example Query

select name from drsql01.test.dbo.employee
  • drslq01 is servernmae --linked serer
  • test is database name
  • dbo is schema -default schema
  • employee is table name

I hope it helps to understand, how to execute query for linked server

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

CGRect Can be simply created using an instance of a CGPoint or CGSize, thats given below.

let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))  

// Or

let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))

Or if we want to specify each value in CGFloat or Double or Int, we can use this method.

let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int

CGPoint Can be created like this.

 let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int

CGSize Can be created like this.

let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int

Also size and point with 0 as the values, it can be done like this.

let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero

CGRectZero & CGPointZero replaced with CGRect.zero & CGPoint.zero in Swift 3.0.

How can I Remove .DS_Store files from a Git repository?

create a .gitignore file using command touch .gitignore

and add the following lines in it

.DS_Store

save the .gitignore file and then push it in to your git repo.

Change <select>'s option and trigger events with JavaScript

html using Razor:

 @Html.DropDownList("test1", Model.SelectOptionList, new { id = "test1", onchange = "myFunction()" })

JS Code:

function myFunction() {

            var value = document.getElementById('test1').value;

            console.log("it has been changed! to " + value );
        }

How can I find last row that contains data in a specific column?

The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.

Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)

sql ORDER BY multiple values in specific order?

Since i don't have enough reputation to write as a comment, added this as a new answer.

You can add asc or desc to order by clause.

ORDER BY x_field='A' ASC, x_field='I' DESC, x_field='P' DESC, x_field='F' ASC

which makes I first, P second and A as last one and F before the last.

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

Fixing npm path in Windows 8 and 10

If, like me, you have MSYS_NO_PATHCONV = 1 configured as a user variable for Git Bash, this issue will be triggered. To workaround, you can either remove this variable or use a different shell (PowerShell) for npm.

Why do we have to override the equals() method in Java?

Let me give you an example that I find very helpful.

You can think of reference as the page number of a book. Suppose now you have two pages a and b like below.

BookPage a = getSecondPage();

BookPage b = getThirdPage();

In this case, a == b will give you false. But, why? The reason is that what == is doing is like comparing the page number. So, even if the content on these two pages is exactly the same, you will still get false.

But what do we do if you we want to compare the content?

The answer is to write your own equals method and specify what you really want to compare.

PHP Fatal Error Failed opening required File

Hey I just had this problem and found that I wasn't looking at the folder location closely enough:

I had

require_once /vagrant/public/liberate/**APP**/vendor/autoload.php

What worked was:

require_once /vagrant/public/liberate/vendor/autoload.php

It was very easy (as a beginner) to overlook this very unnoticeable issue. Yes I do realize that the require issue being logged points directly to the issue at hand, but if you are a beginner, like me, these things can be easily overlooked.

FIX:

Have a good look at the debug of ( __ Dir __ '/etc/etc/etc/file.php') then have your file system open in a different window, and map the two directly. If there is even the slightest difference this require will not work and the above error will be spat out.

Youtube autoplay not working on mobile devices with embedded HTML5 player

The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    </head>
  <body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      width: '100%',
      videoId: 'osz5tVY97dQ',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>
  </body>
</html>

How can I create a memory leak in Java?

I thought it was interesting that no one used the internal class examples. If you have an internal class; it inherently maintains a reference to the containing class. Of course it is not technically a memory leak because Java WILL eventually clean it up; but this can cause classes to hang around longer than anticipated.

public class Example1 {
  public Example2 getNewExample2() {
    return this.new Example2();
  }
  public class Example2 {
    public Example2() {}
  }
}

Now if you call Example1 and get an Example2 discarding Example1, you will inherently still have a link to an Example1 object.

public class Referencer {
  public static Example2 GetAnExample2() {
    Example1 ex = new Example1();
    return ex.getNewExample2();
  }

  public static void main(String[] args) {
    Example2 ex = Referencer.GetAnExample2();
    // As long as ex is reachable; Example1 will always remain in memory.
  }
}

I've also heard a rumor that if you have a variable that exists for longer than a specific amount of time; Java assumes that it will always exist and will actually never try to clean it up if cannot be reached in code anymore. But that is completely unverified.

Maven: add a dependency to a jar by relative path

This is another method in addition to my previous answer at Can I add jars to maven 2 build classpath without installing them?

This will get around the limit when using multi-module builds especially if the downloaded JAR is referenced in child projects outside of the parent. This also reduces the setup work by creating the POM and the SHA1 files as part of the build. It also allows the file to reside anywhere in the project without fixing the names or following the maven repository structure.

This uses the maven-install-plugin. For this to work, you need to set up a multi-module project and have a new project representing the build to install files into the local repository and ensure that one is first.

You multi-module project pom.xml would look like this:

<packaging>pom</packaging>
<modules>
<!-- The repository module must be first in order to ensure
     that the local repository is populated -->
    <module>repository</module>
    <module>... other modules ...</module>
</modules>

The repository/pom.xml file will then contain the definitions to load up the JARs that are part of your project. The following are some snippets of the pom.xml file.

<artifactId>repository</artifactId>
<packaging>pom</packaging>

The pom packaging prevents this from doing any tests or compile or generating any jar file. The meat of the pom.xml is in the build section where the maven-install-plugin is used.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
                <execution>
                        <id>com.ibm.db2:db2jcc</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>install-file</goal>
                        </goals>
                        <configuration>
                            <groupId>com.ibm.db2</groupId>
                            <artifactId>db2jcc</artifactId>
                            <version>9.0.0</version>
                            <packaging>jar</packaging>
                            <file>${basedir}/src/jars/db2jcc.jar</file>
                            <createChecksum>true</createChecksum>
                            <generatePom>true</generatePom>
                        </configuration>
                </execution>
                <execution>...</execution>
            </executions>
        </plugin>
    </plugins>
</build>

To install more than one file, just add more executions.

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

how to check if string value is in the Enum list?

You can use the TryParse method that returns true if it successful:

Age age;

if(Enum.TryParse<Age>("myString", out age))
{
   //Here you can use age
}

Python 3 - Encode/Decode vs Bytes/Str

Neither is better than the other, they do exactly the same thing. However, using .encode() and .decode() is the more common way to do it. It is also compatible with Python 2.

Read Session Id using Javascript

Yes. As the session ID is either transported over the URL (document.location.href) or via a cookie (document.cookie), you could check both for the presence of a session ID.

Selecting only numeric columns from a data frame

EDIT: updated to avoid use of ill-advised sapply.

Since a data frame is a list we can use the list-apply functions:

nums <- unlist(lapply(x, is.numeric))  

Then standard subsetting

x[ , nums]

## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)

For a more idiomatic modern R I'd now recommend

x[ , purrr::map_lgl(x, is.numeric)]

Less codey, less reflecting R's particular quirks, and more straightforward, and robust to use on database-back-ended tibbles:

dplyr::select_if(x, is.numeric)

Newer versions of dplyr, also support the following syntax:

x %>% dplyr::select(where(is.numeric))

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Graphviz's executables are not found (Python 3.4)

I also had this problem on Ubuntu 16.04.

Fixed by running sudo apt-get install graphviz in addition to the pip install I had already performed.

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test

close fancy box from function from within open 'fancybox'

After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close() and I made it an inline script on an onClick. Going to check if i can call it from the parent

Why am I getting string does not name a type Error?

Just use the std:: qualifier in front of string in your header files.

In fact, you should use it for istream and ostream also - and then you will need #include <iostream> at the top of your header file to make it more self contained.

How to convert hex to rgb using Java?

Actually, there's an easier (built in) way of doing this:

Color.decode("#FFCCEE");

Spring Boot - How to log all requests and responses with exceptions in single place?

If you dont mind trying Spring AOP, this is something I have been exploring for logging purposes and it works pretty well for me. It wont log requests that have not been defined and failed request attempts though.

Add these three dependencies

spring-aop, aspectjrt, aspectjweaver

Add this to your xml config file <aop:aspectj-autoproxy/>

Create an annotation which can be used as a pointcut

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface EnableLogging {
ActionType actionType();
}

Now annotate all your rest API methods which you want to log

@EnableLogging(actionType = ActionType.SOME_EMPLOYEE_ACTION)
@Override
public Response getEmployees(RequestDto req, final String param) {
...
}

Now on to the Aspect. component-scan the package which this class is in.

@Aspect
@Component
public class Aspects {

@AfterReturning(pointcut = "execution(@co.xyz.aspect.EnableLogging * *(..)) && @annotation(enableLogging) && args(reqArg, reqArg1,..)", returning = "result")
public void auditInfo(JoinPoint joinPoint, Object result, EnableLogging enableLogging, Object reqArg, String reqArg1) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();

    if (result instanceof Response) {
        Response responseObj = (Response) result;

    String requestUrl = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + request.getContextPath() + request.getRequestURI()
                + "?" + request.getQueryString();

String clientIp = request.getRemoteAddr();
String clientRequest = reqArg.toString();
int httpResponseStatus = responseObj.getStatus();
responseObj.getEntity();
// Can log whatever stuff from here in a single spot.
}


@AfterThrowing(pointcut = "execution(@co.xyz.aspect.EnableLogging * *(..)) && @annotation(enableLogging) && args(reqArg, reqArg1,..)", throwing="exception")
public void auditExceptionInfo(JoinPoint joinPoint, Throwable exception, EnableLogging enableLogging, Object reqArg, String reqArg1) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();

    String requestUrl = request.getScheme() + "://" + request.getServerName()
    + ":" + request.getServerPort() + request.getContextPath() + request.getRequestURI()
    + "?" + request.getQueryString();

    exception.getMessage();
    exception.getCause();
    exception.printStackTrace();
    exception.getLocalizedMessage();
    // Can log whatever exceptions, requests, etc from here in a single spot.
    }
}

@AfterReturning advice runs when a matched method execution returns normally.

@AfterThrowing advice runs when a matched method execution exits by throwing an exception.

If you want to read in detail read through this. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

Run JavaScript in Visual Studio Code

Follow these steps in VS code.[performed in windows os]

  1. Create new file

  2. Write javascript codes in it

  3. Save file as filename.js

  4. Go to Debugging menu

  5. Click on Start debugging

  6. or simply press F5

screenshot of starting debugging

screenshot of output of js code in terminal

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

Git merge reports "Already up-to-date" though there is a difference

This often happens to me when I know there are changes on the remote master, so I try to merge them using git merge master. However, this doesn't merge with the remote master, but with your local master.

So before doing the merge, checkout master, and then git pull there. Then you will be able to merge the new changes into your branch.

How does a hash table work?

All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.

As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.

Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.

In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Getting HTTP code in PHP using curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$rt = curl_exec($ch);
$info = curl_getinfo($ch);
echo $info["http_code"];

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

PHP How to find the time elapsed since a date time?

You can get a function for this directly form WordPress core files take a look here

http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/formatting.php#L2121

function human_time_diff( $from, $to = '' ) {
    if ( empty( $to ) )
        $to = time();

    $diff = (int) abs( $to - $from );

    if ( $diff < HOUR_IN_SECONDS ) {
        $mins = round( $diff / MINUTE_IN_SECONDS );
        if ( $mins <= 1 )
            $mins = 1;
        /* translators: min=minute */
        $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
    } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
        $hours = round( $diff / HOUR_IN_SECONDS );
        if ( $hours <= 1 )
            $hours = 1;
        $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
    } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
        $days = round( $diff / DAY_IN_SECONDS );
        if ( $days <= 1 )
            $days = 1;
        $since = sprintf( _n( '%s day', '%s days', $days ), $days );
    } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
        $weeks = round( $diff / WEEK_IN_SECONDS );
        if ( $weeks <= 1 )
            $weeks = 1;
        $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
    } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
        $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
        if ( $months <= 1 )
            $months = 1;
        $since = sprintf( _n( '%s month', '%s months', $months ), $months );
    } elseif ( $diff >= YEAR_IN_SECONDS ) {
        $years = round( $diff / YEAR_IN_SECONDS );
        if ( $years <= 1 )
            $years = 1;
        $since = sprintf( _n( '%s year', '%s years', $years ), $years );
    }

    return $since;
}

jQuery get value of select onChange

jQuery get value of select html elements using on Change event

For Demo & More Example

_x000D_
_x000D_
$(document).ready(function () {   _x000D_
    $('body').on('change','#select_box', function() {_x000D_
         $('#show_only').val(this.value);_x000D_
    });_x000D_
}); 
_x000D_
<!DOCTYPE html>  _x000D_
<html>  _x000D_
<title>jQuery Select OnChnage Method</title>_x000D_
<head> _x000D_
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>    _x000D_
</head>  _x000D_
<body>  _x000D_
<select id="select_box">_x000D_
 <option value="">Select One</option>_x000D_
    <option value="One">One</option>_x000D_
    <option value="Two">Two</option>_x000D_
    <option value="Three">Three</option>_x000D_
    <option value="Four">Four</option>_x000D_
    <option value="Five">Five</option>_x000D_
</select>_x000D_
<br><br>  _x000D_
<input type="text" id="show_only" disabled="">_x000D_
</body>  _x000D_
</html>  
_x000D_
_x000D_
_x000D_

Split string by single spaces

You could also just use the old fashion 'strtok'

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Its a bit wonky but doesn't involve using boost (not that boost is a bad thing).

You basically call strtok with the string you want to split and the delimiter (in this case a space) and it will return you a char*.

From the link:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

How do I get the MAX row with a GROUP BY in LINQ query?

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
    {
        Serial_Number = g.Key,
        uid = g.Max(row => row.uid)
    });

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Here are some more tests

True if string is not empty:

[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"

True if string is empty:

[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"

Copy the entire contents of a directory in C#

Better than any code (extension method to DirectoryInfo with recursion)

public static bool CopyTo(this DirectoryInfo source, string destination)
    {
        try
        {
            foreach (string dirPath in Directory.GetDirectories(source.FullName))
            {
                var newDirPath = dirPath.Replace(source.FullName, destination);
                Directory.CreateDirectory(newDirPath);
                new DirectoryInfo(dirPath).CopyTo(newDirPath);
            }
            //Copy all the files & Replaces any files with the same name
            foreach (string filePath in Directory.GetFiles(source.FullName))
            {
                File.Copy(filePath, filePath.Replace(source.FullName,destination), true);
            }
            return true;
        }
        catch (IOException exp)
        {
            return false;
        }
    }

jQuery .val change doesn't change input value

Changing the value property does not change the defaultValue. In the code (retrieved with .html() or innerHTML) the value attribute will contain the defaultValue, not the value property.

Calculate time difference in Windows batch file

Using a single function with the possibility of custom unit of measure or formatted. Each time the function is called without parameters we restarted the initial time.

@ECHO OFF

ECHO.
ECHO DEMO timer function
ECHO --------------------

SET DELAY=4

:: First we call the function without any parameters to set the starting time
CALL:timer

:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.

ping -n %DELAY% -w 1 127.0.0.1 >NUL

:: Now we call the function again with the desired parameters

CALL:timer elapsed_time

ECHO by Default : %elapsed_time%

CALL:timer elapsed_time "s"

ECHO in Seconds : %elapsed_time%

CALL:timer elapsed_time "anything"

ECHO Formatted  : %elapsed_time%  (HH:MM:SS.CS)

ECHO.
PAUSE


:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters 
:: to be in another unit of measure or with formatted
::
::  Parameters:
::             <return>     the returned value
::             [formatted]  s (for seconds), m (for minutes), h (for hours)
::                          anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
    SetLocal EnableExtensions EnableDelayedExpansion

    SET _t=%time%
    SET _t=%_t::0=: %
    SET _t=%_t:,0=, %
    SET _t=%_t:.0=. %
    SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
    SET /A _t=%_t%

    :: If we call the function without parameters is defined initial time
    SET _r=%~1
    IF NOT DEFINED _r (
        EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
    )

    SET /A _t=%_t% - %TIMER_START_TIME%

    :: In the case of wanting a formatted output
    SET _f=%~2
    IF DEFINED _f (

        IF "%_f%" == "s" (

            SET /A "_t=%_t% / 100"

        ) ELSE (
            IF "%_f%" == "m" (

                SET /A "_t=%_t% / 6000"

            ) ELSE (

                IF "%_f%" == "h" (

                    SET /A "_t=%_t% / 360000"

                ) ELSE (

                    SET /A "_h=%_t% / 360000"
                    SET /A "_m=(%_t% - !_h! * 360000) / 6000"
                    SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
                    SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"

                    IF !_h! LSS 10 SET "_h=0!_h!"
                    IF !_m! LSS 10 SET "_m=0!_m!"
                    IF !_s! LSS 10 SET "_s=0!_s!"
                    IF !_cs! LSS 10 SET "_cs=0!_cs!"
                    SET "_t=!_h!:!_m!:!_s!.!_cs!"
                    SET "_t=!_t:00:=!"

                )
            )
        )
    )

    EndLocal & SET %~1=%_t%
goto :EOF

A test with a delay of 94 sec

DEMO timer function
--------------------

Making some delay, please wait...

by Default : 9404
in Seconds : 94
Formatted  : 01:34.05  (HH:MM:SS.CS)

Presione una tecla para continuar . . .

Is it possible to override / remove background: none!important with jQuery?

Any !important can be overridden by another !important, the normal CSS precedence rules still apply.

Example:

#an-element{
    background: #F00 !important;
}
#an-element{
    background: #0F0 !important; //Makes #an-element green
}

Then you could add a style attribute (using JavaScript/jQuery) to override the CSS

$(function () {  
    $("#an-element").attr('style', 'background: #00F !important;');
    //Makes #an-element blue
});

See the result here

Stop and Start a service via batch or cmd file?

We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.

The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

But then again...

I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

AddTransient, AddScoped and AddSingleton Services Differences

AddSingleton()

AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.

AddScoped()

In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request. But every new HTTP request will get a new instance of the service.

AddTransient()

With a transient service, a new instance is provided every time a service instance is requested whether it is in the scope of the same HTTP request or across different HTTP requests.

Height of an HTML select box (dropdown)

NO. It's not possible to change height of a select dropdown because that property is browser specific.

However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu and define it's max-height property. Something like this.

_x000D_
_x000D_
$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
    var text = $(this).html();_x000D_
    var htmlText = text + ' <span class="caret"></span>';_x000D_
    $(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);_x000D_
});
_x000D_
.dropdown-menu {_x000D_
    max-height: 146px;_x000D_
    overflow: scroll;_x000D_
    overflow-x: hidden;_x000D_
    margin-top: 0px;_x000D_
}_x000D_
_x000D_
.caret {_x000D_
   float: right;_x000D_
    margin-top: 5%;_x000D_
}_x000D_
_x000D_
#menu1 {_x000D_
    width: 160px; _x000D_
    text-align: left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
   _x000D_
<div class="container" style="margin:10px">_x000D_
  <div class="dropdown">_x000D_
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
    <span class="caret"></span></button>_x000D_
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JQuery Ajax Post results in 500 Internal Server Error

Your code contains dataType: json.

In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.

The server should return a response of null or {} instead.

Setting Windows PATH for Postgres tools

Set path For PostgreSQL in Windows:

  1. Searching for env will show Edit environment variables for your account
  2. Select Environment Variables
  3. From the System Variables box select PATH
  4. Click New (to add new path)

Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]

C:\Program Files\PostgreSQL\12\bin

After that click OK

Open CMD/Command Prompt. Type this to open psql

psql -U username database_name

For Example psql -U postgres test

Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).

Then you are good to go.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

If my interface must return Task what is the best way to have a no-operation implementation?

Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

I checked all the answers but informing only to kill PID.

In case if you have terminal access shared by all it will not help or maybe you do not have permission to kill PID.

In this case what you can do is:

Double click on server

Go to Overview and change ports in Ports like this:

enter image description here

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

Drop data frame columns by name

DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
DF

Output:

    x  y z  a
1   1 10 5 11
2   2  9 5 12
3   3  8 5 13
4   4  7 5 14
5   5  6 5 15
6   6  5 5 16
7   7  4 5 17
8   8  3 5 18
9   9  2 5 19
10 10  1 5 20

DF[c("a","x")] <- list(NULL)

Output:

        y z
    1  10 5
    2   9 5
    3   8 5
    4   7 5
    5   6 5
    6   5 5
    7   4 5
    8   3 5    
    9   2 5
    10  1 5

How can I run Tensorboard on a remote server?

Another option if you can't get it working for some reason is to simply mount a logdir directory on your filesystem with sshfs:

sshfs user@host:/home/user/project/summary_logs ~/summary_logs

and then run Tensorboard locally.

Why plt.imshow() doesn't display the image?

plt.imshow displays the image on the axes, but if you need to display multiple images you use show() to finish the figure. The next example shows two figures:

import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()

In Google Colab, if you comment out the show() method from previous example just a single image will display (the later one connected with X_train[1]).

Here is the content from the help:

plt.show(*args, **kw)
        Display a figure.
        When running in ipython with its pylab mode, display all
        figures and return to the ipython prompt.

        In non-interactive mode, display all figures and block until
        the figures have been closed; in interactive mode it has no
        effect unless figures were created prior to a change from
        non-interactive to interactive mode (not recommended).  In
        that case it displays the figures but does not block.

        A single experimental keyword argument, *block*, may be
        set to True or False to override the blocking behavior
        described above.



plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
        Display an image on the axes.

Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
    Display the image in `X` to current axes.  `X` may be an
    array or a PIL image. If `X` is an array, it
    can have the following shapes and types:

    - MxN -- values to be mapped (float or int)
    - MxNx3 -- RGB (float or uint8)
    - MxNx4 -- RGBA (float or uint8)

    The value for each component of MxNx3 and MxNx4 float arrays
    should be in the range 0.0 to 1.0. MxN arrays are mapped
    to colors based on the `norm` (mapping scalar to scalar)
    and the `cmap` (mapping the normed scalar to a color).

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

How to have Java method return generic list of any type?

No need to even pass the class:

public <T> List<T> magicalListGetter() {
    return new ArrayList<T>();
}

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Python Flask, how to set content type

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse