Programs & Examples On #Desktop application

An application that runs stand alone in a desktop or laptop computer. Contrast with "Web-based application," which requires the Web browser to run.

Executable directory where application is running from?

Dim strPath As String = System.IO.Path.GetDirectoryName( _
    System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

Taken from HOW TO: Determine the Executing Application's Path (MSDN)

How to develop Desktop Apps using HTML/CSS/JavaScript?

Awesomium makes it easy to use HTML UI in your C++ or .NET app

Update

My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.

How to fit Windows Form to any screen resolution?

Probably a maximized Form helps, or you can do this manually upon form load:

Code Block

this.Location = new Point(0, 0);

this.Size = Screen.PrimaryScreen.WorkingArea.Size;

And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.

Hope this helps,

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

How can I have same rule for two locations in NGINX config?

Try

location ~ ^/(first/location|second/location)/ {
  ...
}

The ~ means to use a regular expression for the url. The ^ means to check from the first character. This will look for a / followed by either of the locations and then another /.

Java - Get a list of all Classes loaded in the JVM

It's not a programmatic solution but you can run

java -verbose:class ....

and the JVM will dump out what it's loading, and from where.

[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]

See here for more details.

What are Covering Indexes and Covered Queries in SQL Server?

A covering query is on where all the predicates can be matched using the indices on the underlying tables.

This is the first step towards improving the performance of the sql under consideration.

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

Android: Center an image

If you are using a LinearLayout , use the gravity attribute :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView android:layout_width="wrap_content"
        android:id="@+id/imageView1"
        android:src="@drawable/icon"
        android:layout_height="wrap_content"
        android:scaleType="centerInside" />
</LinearLayout>

If you are using a RelativeLayout , you can use android:layout_centerInParent as follows :

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

    <ImageView android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon"
        android:scaleType="centerInside"
        android:layout_centerInParent="true" />

</RelativeLayout>

CSS3 Transition - Fade out effect

.fadeOut{
    background-color: rgba(255, 0, 0, 0.83);
    border-radius: 8px;
    box-shadow: silver 3px 3px 5px 0px;
    border: 2px dashed yellow;
    padding: 3px;
}
.fadeOut.end{
    transition: all 1s ease-in-out;
    background-color: rgba(255, 0, 0, 0.0);
    box-shadow: none;
    border: 0px dashed yellow;
    border-radius: 0px;
}

demo here.

Unicode character as bullet for list-item in CSS

This topic may be old, but here's a quick fix ul {list-style:outside none square;} or ul {list-style:outside none disc;} , etc...

then add left padding to list element

ul li{line-height: 1.4;padding-bottom: 6px;}

How to use bootstrap-theme.css with bootstrap 3?

I know this post is kinda old but...

  As 'witttness' pointed out.

About Your Own Custom Theme You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

  I see it as Bootstrap has seen over the years that everyone wants something a bit different than the core styles. While you could modify bootstrap.css it might break things and it could make updating to a newer version a real pain and time consuming. Downloading from a 'theme' site means you have to wait on if that creator updates that theme, big if sometimes, right?

  Some build their own 'custom.css' file and that's ok, but if you use 'bootstrap-theme.css' a lot of stuff is already built and this allows you to roll your own theme faster 'without' disrupting the core of bootstrap.css. I for one don't like the 3D buttons and gradients most of the time, so change them using bootstrap-theme.css. Add margins or padding, change the radius to your buttons, and so on...

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

What is the single most influential book every programmer should read?

SAP ABAP programming? "Teach Yourself ABAP in 21 Days" is the best book!

It contains no clever tricks or wizardry, but after 3 years, I never came upon a more comprehensive book

Run AVD Emulator without Android Studio

If you are starting emulator for Flutter applications, then you can run below command -

> flutter emulators --launch [Emulator ID]

In my case, emulator id is Pixel_2_API_29 as i created it with AVD manager in Android studio. so the command in my case is below -

> flutter emulators --launch Pixel_2_API_29

Thanks

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

How to hide output of subprocess in Python 2.7

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

How to write a switch statement in Ruby

As stated in many of the above answers, the === operator is used under the hood on case/when statements.

Here is additional information about that operator:

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as "case-equality", "triple equals" or "threequals". Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its sub-classes).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job, such as is_a? and instance_of?.

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left.

/zen/ === "practice zazen today"  # Output: => true
# is similar to
"practice zazen today"=~ /zen/

The only relevant difference between the two examples above is that, when there is a match, === returns true and =~ returns an integer, which is a truthy value in Ruby. We will get back to this soon.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

to pass many options you can pass a object to a @Input decorator with custom data in a single line.

In the template

<li *ngFor = 'let opt of currentQuestion.options' 
                [selectable] = 'opt'
                [myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
                (selectedOption) = 'onOptionSelection($event)' >
     {{opt.option}}
</li>

so in Directive class

@Directive({
  selector: '[selectable]'
})

export class SelectableDirective{
  private el: HTMLElement;
  @Input('selectable') option:any;
  @Input('myOptions') data;

  //do something with data.first
  ...
  // do something with data.second
}

Can't push to GitHub because of large file which I already deleted

Here's something I found super helpful if you've already been messing around with your repo before you asked for help. First type:

git status

After this, you should see something along the lines of

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

The important part is the "2 commits"! From here, go ahead and type in:

git reset HEAD~<HOWEVER MANY COMMITS YOU WERE BEHIND>

So, for the example above, one would type:

git reset HEAD~2

After you typed that, your "git status" should say:

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

From there, you can delete the large file (assuming you haven't already done so), and you should be able to re-commit everything without losing your work.
I know this isn't a super fancy reply, but I hope it helps!

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

If you are ubuntu 14.04 and using php 5.6 You are missing out on mbstring and mysql module

Please install mbstring and mysql by

sudo apt-get install php5.6-mbstring
sudo apt-get install php5.6-mysql

and restart apache

sudo service apache2 restart

Dependency injection with Jersey 2.0

Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.version}</version>
    </dependency>

The basic code will be as follows:

@RequestScoped
@Path("test")
public class RESTEndpoint {

   @GET
   public String getMessage() {

Eclipse doesn't stop at breakpoints

I had the same problem, and I found the real cause.

I had written some concurrent / multi-threads code, while I added some breakpoints inside the code running in a new thread. So, when JUnit tests ran over, and stopped soon, the code will not reach and stop at the breakpoints.

For this situation, we have to click and select "Keep JUnit running after a test run when debugging" check box at "Debug Configurations..."

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

How to substitute shell variables in complex text files

Actually you need to change your read to read -r which will make it ignore backslashes.

Also, you should escape quotes and backslashes. So

while read -r line; do
  line="${line//\\/\\\\}"
  line="${line//\"/\\\"}"
  line="${line//\`/\\\`}"
  eval echo "\"$line\""
done > destination.txt < source.txt

Still a terrible way to do expansion though.

PHP - check if variable is undefined

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

This code will output "This line is printed, because the $var1 is set."

read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/

What's the use of ob_start() in php?

The accepted answer here describes what ob_start() does - not why it is used (which was the question asked).

As stated elsewhere ob_start() creates a buffer which output is written to.

But nobody has mentioned that it is possible to stack multiple buffers within PHP. See ob_get_level().

As to the why....

  1. Sending HTML to the browser in larger chunks gives a performance benefit from a reduced network overhead.

  2. Passing the data out of PHP in larger chunks gives a performance and capacity benefit by reducing the number of context switches required

  3. Passing larger chunks of data to mod_gzip/mod_deflate gives a performance benefit in that the compression can be more efficient.

  4. buffering the output means that you can still manipulate the HTTP headers later in the code

  5. explicitly flushing the buffer after outputting the [head]....[/head] can allow the browser to begin marshaling other resources for the page before HTML stream completes.

  6. Capturing the output in a buffer means that it can redirected to other functions such as email, or copied to a file as a cached representation of the content

How to get a table cell value using jQuery?

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

If that makes things easier.

How does PHP 'foreach' actually work?

PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

How to pass data to view in Laravel?

You can pass data to the view using the with method.

return View::make('blog')->with('posts', $posts);

CMD: Export all the screen content to a text file

If your batch file is not interactive and you don't need to see it run then this should work.

@echo off
call file.bat >textfile.txt 2>&1

Otherwise use a tee filter. There are many, some not NT compatible. SFK the Swiss Army Knife has a tee feature and is still being developed. Maybe that will work for you.

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    }
    var url  = window.URL.createObjectURL(file);
    …
}

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

Switching to landscape mode in Android Emulator

In my case, i succeeded by doing this:

1- enable 'Auto-Rotate', if it isn´t yet.
2- either use rotation left-right option at panel located next to the virtual device, or click (ctrl + left/right arrow key), in order to rotate the device.

Hope it works for you.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

How to remove new line characters from data rows in mysql?

your syntax is wrong:

update mytable SET title = TRIM(TRAILING '\n' FROM title)

Addition:

If the newline character is at the start of the field:

update mytable SET title = TRIM(LEADING '\n' FROM title)

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

For Firefox/Chrome users, a nice way to achieve 100% width is to use a custom TamperMonkey script.

The benefits are

  1. configure this once in your browser, no need to modify the server configuration.
  2. works with multiple jupyter servers.
  3. TamperMonkey is trusted, maintained, and stable.
  4. Lots of additional customization is possible via javascript.

This script works for me https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js

Enumerations on PHP

Well, for a simple java like enum in php, I use:

class SomeTypeName {
    private static $enum = array(1 => "Read", 2 => "Write");

    public function toOrdinal($name) {
        return array_search($name, self::$enum);
    }

    public function toString($ordinal) {
        return self::$enum[$ordinal];
    }
}

And to call it:

SomeTypeName::toOrdinal("Read");
SomeTypeName::toString(1);

But I'm a PHP beginner, struggling with the syntax so this might not be the best way. I experimented some with Class Constants, using Reflection to get the constant name from it's value, might be neater.

How to unzip a file in Powershell?

Using expand-archive but auto-creating directories named after the archive:

function unzip ($file) {
    $dirname = (Get-Item $file).Basename
    New-Item -Force -ItemType directory -Path $dirname
    expand-archive $file -OutputPath $dirname -ShowProgress
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Try : java -version , then if you see java 11

try to delete with terminal : cd /Library/Java/JavaVirtualMachines rm -rf openjdk-11.0.1.jdk

if it doesn't try delete manually: 1) click on finder 2) go to folder 3) post /Library/Java/JavaVirtualMachines 4) delete java 11 .

then try java version and you will see : java version "1.8.0_191"

Backporting Python 3 open(encoding="utf-8") to Python 2

Here's one way:

with open("filename.txt", "rb") as f:
    contents = f.read().decode("UTF-8")

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

How can I get a list of locally installed Python modules?

There are many ideas, initially I am pondering on these two:

pip

cons: not always installed

help('modules')

cons: output to console; with broken modules (see ubuntu...) can segfault

I need an easy approach, using basic libraries and compatible with old python 2.x

And I see the light: listmodules.py

Hidden in the documentation source directory in 2.5 is a small script that lists all available modules for a Python installation.

Pros:

uses only imp, sys, os, re, time

designed to run on Python 1.5.2 and newer

the source code is really compact, so you can easy tinkering with it, for example to pass an exception list of buggy modules (don't try to import them)

"Invalid form control" only in Google Chrome

$("...").attr("required"); and $("...").removeAttr("required"); 

didn't work for me until I putted all my jQuery code between that:

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

force line break in html table cell

I suggest you use a wrapper div or paragraph:

<td><p style="width:50%;">Text only allowed to extend 50% of the cell.</p></td>

And you can make a class out of it:

<td class="linebreak"><p>Text only allowed to extend 50% of the cell.</p></td>

td.linebreak p {
    width: 50%;
}

All of this assuming that you meant 50% as in 50% of the cell.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Global Events in Angular

My favorite way to do is by using behavior subject or event emitter (almost the same) in my service to control all my subcomponent.

Using angular cli, run ng g s to create a new service then use a BehaviorSubject or EventEmitter

export Class myService {
#all the stuff that must exist

myString: string[] = [];
contactChange : BehaviorSubject<string[]> = new BehaviorSubject(this.myString);

   getContacts(newContacts) {
     // get your data from a webservices & when you done simply next the value 
    this.contactChange.next(newContacts);
   }
}

When you do that every component using your service as a provider will be aware of the change. Simply subscribe to the result like you do with eventEmitter ;)

export Class myComp {
#all the stuff that exists like @Component + constructor using (private myService: myService)

this.myService.contactChange.subscribe((contacts) => {
     this.contactList += contacts; //run everytime next is called
  }
}

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

how to save and read array of array in NSUserdefaults in swift?

Here is an example of reading and writing a list of objects of type SNStock that implements NSCoding - we have an accessor for the entire list, watchlist, and two methods to add and remove objects, that is addStock(stock: SNStock) and removeStock(stock: SNStock).

import Foundation

class DWWatchlistController {

  private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"

  private let userDefaults: NSUserDefaults

  private(set) var watchlist:[SNStock] {

    get {
      if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
        if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
          return watchlist as! [SNStock]
        }
      }
      return []
    }

    set(watchlist) {
      let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
      userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
      userDefaults.synchronize()
    }
  }

  init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
  }

  func addStock(stock: SNStock) {
    var watchlist = self.watchlist
    watchlist.append(stock)
    self.watchlist = watchlist
  }

  func removeStock(stock: SNStock) {
    var watchlist = self.watchlist
    if let index = find(watchlist, stock) {
      watchlist.removeAtIndex(index)
      self.watchlist = watchlist
    }
  }

}

Remember that your object needs to implement NSCoding or else the encoding won't work. Here is what SNStock looks like:

import Foundation

class SNStock: NSObject, NSCoding
{
  let ticker: NSString
  let name: NSString

  init(ticker: NSString, name: NSString)
  {
    self.ticker = ticker
    self.name = name
  }

  //MARK: NSCoding

  required init(coder aDecoder: NSCoder) {
    self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
    self.name = aDecoder.decodeObjectForKey("name") as! NSString
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(ticker, forKey: "ticker")
    aCoder.encodeObject(name, forKey: "name")
  }

  //MARK: NSObjectProtocol

  override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? SNStock {
      return self.ticker == object.ticker &&
        self.name == object.name
    } else {
      return false
    }
  }

  override var hash: Int {
    return ticker.hashValue
  }
}

Hope this helps!

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

How can I add a line to a file in a shell script?

As far as I understand, you want to prepend column1, column2, column3 to your existing one, two, three.

I would use ed in place of sed, since sed write on the standard output and not in the file.

The command:

printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv

should do the work.

perl -i is worth taking a look as well.

How to set delay in android?

You can use this:

import java.util.Timer;

and for the delay itself, add:

 new Timer().schedule(
                    new TimerTask(){
                
                        @Override
                        public void run(){
                            
                        //if you need some code to run when the delay expires
                        }
                        
                    }, delay);

where the delay variable is in milliseconds; for example set delay to 5000 for a 5-second delay.

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

iOS 7: UITableView shows under status bar

I have done this for Retina/Non-Retina display as

BOOL isRetina = FALSE;

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([[UIScreen mainScreen] scale] == 2.0) {
        isRetina = TRUE;
    } else {
        isRetina = FALSE;
    }
}

if (isRetina) {
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
}

Python SQL query string formatting

sql = """\
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
"""

[edit in responese to comment]
Having an SQL string inside a method does NOT mean that you have to "tabulate" it:

>>> class Foo:
...     def fubar(self):
...         sql = """\
... select *
... from frobozz
... where zorkmids > 10
... ;"""
...         print sql
...
>>> Foo().fubar()
select *
from frobozz
where zorkmids > 10
;
>>>

Add a space (" ") after an element using :after

Explanation

It's worth noting that your code does insert a space

h2::after {
  content: " ";
}

However, it's immediately removed.

From Anonymous inline boxes,

White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.

And from The 'white-space' processing model,

If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.

Solution

So if you don't want the space to be removed, set white-space to pre or pre-wrap.

_x000D_
_x000D_
h2 {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
  content: " ";_x000D_
  white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
_x000D_
_x000D_

Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.

How to select a drop-down menu value with Selenium using Python?

firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)

Where is Java Installed on Mac OS X?

Use unix find function to find javas installed...

sudo find / -name java

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

How can I view array structure in JavaScript with alert()?

EDIT: Firefox and Google Chrome now have a built-in JSON object, so you can just say alert(JSON.stringify(myArray)) without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON object being present in all browsers, but for debugging purposes it's incredibly useful.

I tend to use the jQuery-json plugin as follows:

alert( $.toJSON(myArray) );

This prints the array in a format like

[5, 6, 7, 11]

However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.

Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.

Send Outlook Email Via Python?

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

Will use your local outlook account to send.

Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail is a MailItem Object.

How to convert uint8 Array to base64 Encoded String?

If you are using Node.js then you can use this code to convert Uint8Array to base64

var b64 = Buffer.from(u8).toString('base64');

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Installing tensorflow with anaconda in windows

  • Install Anaconda for Python 3.5 - Can install from here for 64 bit windows

  • Then install TensorFlow from here

(I tried previously with Anaconda for Python 3.6 but failed even after creating Conda env for Python3.5)

Additionally if you want to run a Jupyter Notebook and use TensorFlow in it. Use following steps.

Change to TensorFlow env:

C: > activate tensorflow
(tensorflow) C: > pip install jupyter notebook

Once installed, you can launch Jupyter Notebook and test

(tensorflow) C: > jupyter notebook

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

Reading a plain text file in Java

You can use readAllLines and the join method to get whole file content in one line:

String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));

It uses UTF-8 encoding by default, which reads ASCII data correctly.

Also you can use readAllBytes:

String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);

I think readAllBytes is faster and more precise, because it does not replace new line with \n and also new line may be \r\n. It is depending on your needs which one is suitable.

How can I check if char* variable points to empty string?

if (!*ptr) { /* empty string  */}

similarly

if (*ptr)  { /* not empty */ }

What is the correct syntax of ng-include?

For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).

For example:

Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">

Incorrect: div ng-include src=" 'add-more.html' ">

Method call if not null in C#

I have made this generic extension that I use.

public static class ObjectExtensions {
    public static void With<T>(this T value, Action<T> todo) {
        if (value != null) todo(value);
    }
}

Then I use it like below.

string myString = null;
myString.With((value) => Console.WriteLine(value)); // writes nothing
myString = "my value";
myString.With((value) => Console.WriteLine(value)); // Writes `my value`

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

<embed> vs. <object>

You could also use the iframe method, although this is not cross browser compatible (eg. not working in chromium or android and probably others -> instead prompts to download). It works with dataURL's and normal URLS, not sure if the other examples work with dataURLS (please let me know if the other examples work with dataURLS?)

 <iframe class="page-icon preview-pane" frameborder="0" height="352" width="396" src="data:application/pdf;base64, ..DATAURLHERE!... "></iframe>

Convert data.frame column to a vector?

You do not need as.vector(), but you do need correct indexing: avector <- aframe[ , "a2"]

The one other thing to be aware of is the drop=FALSE option to [:

R> aframe <- data.frame(a1=c1:5, a2=6:10, a3=11:15)
R> aframe
  a1 a2 a3
1  1  6 11
2  2  7 12
3  3  8 13
4  4  9 14
5  5 10 15
R> avector <- aframe[, "a2"]
R> avector
[1]  6  7  8  9 10
R> avector <- aframe[, "a2", drop=FALSE]
R> avector
  a2
1  6
2  7
3  8
4  9
5 10
R> 

How to preview git-pull without doing fetch?

After doing a git fetch, do a git log HEAD..origin/master to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either git log -p HEAD..origin/master to show each patch, or git diff HEAD...origin/master (three dots not two) to show a single diff.

There normally isn't any need to undo a fetch, because doing a fetch only updates the remote branches and none of your branches. If you're not prepared to do a pull and merge in all the remote commits, you can use git cherry-pick to accept only the specific remote commits you want. Later, when you're ready to get everything, a git pull will merge in the rest of the commits.

Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)

What are the true benefits of ExpandoObject?

There are some cases where this is handy. I'll use it for a Modularized shell for instance. Each module defines it's own Configuration Dialog databinded to it's settings. I provide it with an ExpandoObject as it's Datacontext and save the values in my configuration Storage. This way the Configuration Dialog writer just has to Bind to a Value and it's automatically created and saved. (And provided to the module for using these settings of course)

It' simply easier to use than an Dictionary. But everyone should be aware that internally it is just a Dictionary.

It's like LINQ just syntactic sugar, but it makes things easier sometimes.

So to answer your question directly: It's easier to write and easier to read. But technically it essentially is a Dictionary<string,object> (You can even cast it into one to list the values).

ERROR Android emulator gets killed

Go to SDK Manager and see if there are any updates on the emulator & build tools that need to be updated.

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

How to secure database passwords in PHP?

For extremely secure systems we encrypt the database password in a configuration file (which itself is secured by the system administrator). On application/server startup the application then prompts the system administrator for the decryption key. The database password is then read from the config file, decrypted, and stored in memory for future use. Still not 100% secure since it is stored in memory decrypted, but you have to call it 'secure enough' at some point!

Getting full URL of action in ASP.NET MVC

This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

To avoid this, you can do the following:

    public class Url
    {
        public string LocalUrl { get; }

        public Url(string localUrl)
        {
            LocalUrl = localUrl;
        }

        public override string ToString()
        {
            return LocalUrl;
        }
    }

    public abstract class Controller
    {
        public Url RootAction => new Url(GetUrl());

        protected abstract string Root { get; }

        public Url BuildAction(string actionName)
        {
            var localUrl = GetUrl() + "/" + actionName;
            return new Url(localUrl);
        }

        private string GetUrl()
        {
            if (Root == "")
            {
                return "";
            }

            return "/" + Root;
        }

        public override string ToString()
        {
            return GetUrl();
        }
    }

Then create your controllers, say for example the DataController:

    public static readonly DataController Data = new DataController();
    public class DataController : Controller
    {
        public const string DogAction = "dog";
        public const string CatAction = "cat";
        public const string TurtleAction = "turtle";

        protected override string Root => "data";

        public Url Dog => BuildAction(DogAction);
        public Url Cat => BuildAction(CatAction);
        public Url Turtle => BuildAction(TurtleAction);
    }

Then just use it like:

    // GET: Data/Cat
    [ActionName(ControllerRoutes.DataController.CatAction)]
    public ActionResult Etisys()
    {
        return View();
    }

And from your .cshtml (or any code)

<ul>
    <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
    <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>

This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

To show a new Form on click of a button in C#

Try this:

private void Button1_Click(Object sender, EventArgs e ) 
{
   var myForm = new Form1();
   myForm.Show();
}

How can I include all JavaScript files in a directory via JavaScript file?

@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:

javascripts.php:

<?php
   //sets the content type to javascript 
   header('Content-type: text/javascript');

   // includes all js files of the directory
   foreach(glob("packages/*.js") as $file) {
      readfile($file);
   }
?>


index.php:

<script type="text/javascript" src="javascripts.php"></script>

That's it!
Have fun! :)

Cannot connect to local SQL Server with Management Studio

Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.

With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?

In my log I see entries like this...

Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]

As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.

jQuery - simple input validation - "empty" and "not empty"

You could do this

$("#input").blur(function(){
    if($(this).val() == ''){
        alert('empty'); 
    }
});

http://jsfiddle.net/jasongennaro/Y5P9k/1/

When the input has lost focus that is .blur(), then check the value of the #input.

If it is empty == '' then trigger the alert.

nodejs get file name from absolute path?

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

C# Listbox Item Double Click Event

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    int index = this.listBox1.IndexFromPoint(e.Location);
    if (index != System.Windows.Forms.ListBox.NoMatches)
    {
        MessageBox.Show(index.ToString());
    }
}

This should work...check

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

How to Get Element By Class in JavaScript?

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

How can I drop all the tables in a PostgreSQL database?

well, since I like working from the command line...

psql -U <user> -d <mydb> -c '\dt' | cut -d ' ' -f 4 | sed -e "s/^/drop table if exists /" | sed -e "s/$/;/"

-c '\dt' will invoke the list tables command.

List of relations Schema | Name | Type | Owner --------+-------------------+-------+---------- public | _d_psidxddlparm | table | djuser public | _d_psindexdefn | table | djuser

cut -d ' ' -f 4 now, pipe its output to grab the 4th field (when using space as separator), which is the table.

sed is then used to prefix a drop table and suffix the ; command separator.

| egrep '_d_' - Pipe it into grep some more and you can be more selective about which tables you drop.

drop table if exists _d_psidxddlparm; drop table if exists _d_psindexdefn;

Note: as written, this will generate bogus rows for the \dt commands output of column headers and total rows at the end. I avoid that by grepping, but you could use head and tail.

What is the difference between user and kernel modes in operating systems?

CPU rings are the most clear distinction

In x86 protected mode, the CPU is always in one of 4 rings. The Linux kernel only uses 0 and 3:

  • 0 for kernel
  • 3 for users

This is the most hard and fast definition of kernel vs userland.

Why Linux does not use rings 1 and 2: CPU Privilege Rings: Why rings 1 and 2 aren't used?

How is the current ring determined?

The current ring is selected by a combination of:

  • global descriptor table: a in-memory table of GDT entries, and each entry has a field Privl which encodes the ring.

    The LGDT instruction sets the address to the current descriptor table.

    See also: http://wiki.osdev.org/Global_Descriptor_Table

  • the segment registers CS, DS, etc., which point to the index of an entry in the GDT.

    For example, CS = 0 means the first entry of the GDT is currently active for the executing code.

What can each ring do?

The CPU chip is physically built so that:

  • ring 0 can do anything

  • ring 3 cannot run several instructions and write to several registers, most notably:

    • cannot change its own ring! Otherwise, it could set itself to ring 0 and rings would be useless.

      In other words, cannot modify the current segment descriptor, which determines the current ring.

    • cannot modify the page tables: How does x86 paging work?

      In other words, cannot modify the CR3 register, and paging itself prevents modification of the page tables.

      This prevents one process from seeing the memory of other processes for security / ease of programming reasons.

    • cannot register interrupt handlers. Those are configured by writing to memory locations, which is also prevented by paging.

      Handlers run in ring 0, and would break the security model.

      In other words, cannot use the LGDT and LIDT instructions.

    • cannot do IO instructions like in and out, and thus have arbitrary hardware accesses.

      Otherwise, for example, file permissions would be useless if any program could directly read from disk.

      More precisely thanks to Michael Petch: it is actually possible for the OS to allow IO instructions on ring 3, this is actually controlled by the Task state segment.

      What is not possible is for ring 3 to give itself permission to do so if it didn't have it in the first place.

      Linux always disallows it. See also: Why doesn't Linux use the hardware context switch via the TSS?

How do programs and operating systems transition between rings?

  • when the CPU is turned on, it starts running the initial program in ring 0 (well kind of, but it is a good approximation). You can think this initial program as being the kernel (but it is normally a bootloader that then calls the kernel still in ring 0).

  • when a userland process wants the kernel to do something for it like write to a file, it uses an instruction that generates an interrupt such as int 0x80 or syscall to signal the kernel. x86-64 Linux syscall hello world example:

    .data
    hello_world:
        .ascii "hello world\n"
        hello_world_len = . - hello_world
    .text
    .global _start
    _start:
        /* write */
        mov $1, %rax
        mov $1, %rdi
        mov $hello_world, %rsi
        mov $hello_world_len, %rdx
        syscall
    
        /* exit */
        mov $60, %rax
        mov $0, %rdi
        syscall
    

    compile and run:

    as -o hello_world.o hello_world.S
    ld -o hello_world.out hello_world.o
    ./hello_world.out
    

    GitHub upstream.

    When this happens, the CPU calls an interrupt callback handler which the kernel registered at boot time. Here is a concrete baremetal example that registers a handler and uses it.

    This handler runs in ring 0, which decides if the kernel will allow this action, do the action, and restart the userland program in ring 3. x86_64

  • when the exec system call is used (or when the kernel will start /init), the kernel prepares the registers and memory of the new userland process, then it jumps to the entry point and switches the CPU to ring 3

  • If the program tries to do something naughty like write to a forbidden register or memory address (because of paging), the CPU also calls some kernel callback handler in ring 0.

    But since the userland was naughty, the kernel might kill the process this time, or give it a warning with a signal.

  • When the kernel boots, it setups a hardware clock with some fixed frequency, which generates interrupts periodically.

    This hardware clock generates interrupts that run ring 0, and allow it to schedule which userland processes to wake up.

    This way, scheduling can happen even if the processes are not making any system calls.

What is the point of having multiple rings?

There are two major advantages of separating kernel and userland:

  • it is easier to make programs as you are more certain one won't interfere with the other. E.g., one userland process does not have to worry about overwriting the memory of another program because of paging, nor about putting hardware in an invalid state for another process.
  • it is more secure. E.g. file permissions and memory separation could prevent a hacking app from reading your bank data. This supposes, of course, that you trust the kernel.

How to play around with it?

I've created a bare metal setup that should be a good way to manipulate rings directly: https://github.com/cirosantilli/x86-bare-metal-examples

I didn't have the patience to make a userland example unfortunately, but I did go as far as paging setup, so userland should be feasible. I'd love to see a pull request.

Alternatively, Linux kernel modules run in ring 0, so you can use them to try out privileged operations, e.g. read the control registers: How to access the control registers cr0,cr2,cr3 from a program? Getting segmentation fault

Here is a convenient QEMU + Buildroot setup to try it out without killing your host.

The downside of kernel modules is that other kthreads are running and could interfere with your experiments. But in theory you can take over all interrupt handlers with your kernel module and own the system, that would be an interesting project actually.

Negative rings

While negative rings are not actually referenced in the Intel manual, there are actually CPU modes which have further capabilities than ring 0 itself, and so are a good fit for the "negative ring" name.

One example is the hypervisor mode used in virtualization.

For further details see:

ARM

In ARM, the rings are called Exception Levels instead, but the main ideas remain the same.

There exist 4 exception levels in ARMv8, commonly used as:

  • EL0: userland

  • EL1: kernel ("supervisor" in ARM terminology).

    Entered with the svc instruction (SuperVisor Call), previously known as swi before unified assembly, which is the instruction used to make Linux system calls. Hello world ARMv8 example:

    hello.S

    .text
    .global _start
    _start:
        /* write */
        mov x0, 1
        ldr x1, =msg
        ldr x2, =len
        mov x8, 64
        svc 0
    
        /* exit */
        mov x0, 0
        mov x8, 93
        svc 0
    msg:
        .ascii "hello syscall v8\n"
    len = . - msg
    

    GitHub upstream.

    Test it out with QEMU on Ubuntu 16.04:

    sudo apt-get install qemu-user gcc-arm-linux-gnueabihf
    arm-linux-gnueabihf-as -o hello.o hello.S
    arm-linux-gnueabihf-ld -o hello hello.o
    qemu-arm hello
    

    Here is a concrete baremetal example that registers an SVC handler and does an SVC call.

  • EL2: hypervisors, for example Xen.

    Entered with the hvc instruction (HyperVisor Call).

    A hypervisor is to an OS, what an OS is to userland.

    For example, Xen allows you to run multiple OSes such as Linux or Windows on the same system at the same time, and it isolates the OSes from one another for security and ease of debug, just like Linux does for userland programs.

    Hypervisors are a key part of today's cloud infrastructure: they allow multiple servers to run on a single hardware, keeping hardware usage always close to 100% and saving a lot of money.

    AWS for example used Xen until 2017 when its move to KVM made the news.

  • EL3: yet another level. TODO example.

    Entered with the smc instruction (Secure Mode Call)

The ARMv8 Architecture Reference Model DDI 0487C.a - Chapter D1 - The AArch64 System Level Programmer's Model - Figure D1-1 illustrates this beautifully:

enter image description here

The ARM situation changed a bit with the advent of ARMv8.1 Virtualization Host Extensions (VHE). This extension allows the kernel to run in EL2 efficiently:

enter image description here

VHE was created because in-Linux-kernel virtualization solutions such as KVM have gained ground over Xen (see e.g. AWS' move to KVM mentioned above), because most clients only need Linux VMs, and as you can imagine, being all in a single project, KVM is simpler and potentially more efficient than Xen. So now the host Linux kernel acts as the hypervisor in those cases.

Note how ARM, maybe due to the benefit of hindsight, has a better naming convention for the privilege levels than x86, without the need for negative levels: 0 being the lower and 3 highest. Higher levels tend to be created more often than lower ones.

The current EL can be queried with the MRS instruction: what is the current execution mode/exception level, etc?

ARM does not require all exception levels to be present to allow for implementations that don't need the feature to save chip area. ARMv8 "Exception levels" says:

An implementation might not include all of the Exception levels. All implementations must include EL0 and EL1. EL2 and EL3 are optional.

QEMU for example defaults to EL1, but EL2 and EL3 can be enabled with command line options: qemu-system-aarch64 entering el1 when emulating a53 power up

Code snippets tested on Ubuntu 18.10.

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Android Studio - Gradle sync project failed

In my case NDK location was the issue.

go to File->Project Structure->SDK Location and add NDK location

How to change options of <select> with jQuery?

I threw CMS's excellent answer into a quick jQuery extension:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(jQuery, window);

It expects an array of objects which contain "text" and "value" keys. So usage is as follows:

var options = [
  {text: "one", value: 1},
  {text: "two", value: 2}
];

$("#foo").replaceOptions(options);

javascript cell number validation

function IsMobileNumber(txtMobId) {
    var mob = /^[1-9]{1}[0-9]{9}$/;
    var txtMobile = document.getElementById(txtMobId);
    if (mob.test(txtMobile.value) == false) {
        alert("Please enter valid mobile number.");
        txtMobile.focus();
        return false;
    }
    return true;
}

Calling Validation Mobile Number Function HTML Code -

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Swift Beta performance: sorting arrays

Swift 4.1 introduces new -Osize optimization mode.

In Swift 4.1 the compiler now supports a new optimization mode which enables dedicated optimizations to reduce code size.

The Swift compiler comes with powerful optimizations. When compiling with -O the compiler tries to transform the code so that it executes with maximum performance. However, this improvement in runtime performance can sometimes come with a tradeoff of increased code size. With the new -Osize optimization mode the user has the choice to compile for minimal code size rather than for maximum speed.

To enable the size optimization mode on the command line, use -Osize instead of -O.

Further reading : https://swift.org/blog/osize/

Hive query output to file

This command will redirect the output to a text file of your choice:

$hive -e "select * from table where id > 10" > ~/sample_output.txt

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Javascript

This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.

<script>
    if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
</script>

remove objects from array by object property

You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:

arrayOfObjects = arrayOfObjects.filter(obj => obj.id != idToRemove)

How can I call a shell command in my Perl script?

As you become more experienced with using Perl, you'll find that there are fewer and fewer occasions when you need to run shell commands. For example, one way to get a list of files is to use Perl's built-in glob function. If you want the list in sorted order you could combine it with the built-in sort function. If you want details about each file, you can use the stat function. Here's an example:

#!/usr/bin/perl

use strict;
use warnings;

foreach my $file ( sort glob('/home/grant/*') ) {
    my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
        = stat($file);
    printf("%-40s %8u bytes\n", $file, $size);
}

Using Docker-Compose, how to execute multiple commands

try using ";" to separate the commands if you are in verions two e.g.

command: "sleep 20; echo 'a'"

How to convert an integer to a string in any base?

>>> import string
>>> def int2base(integer, base):
        if not integer: return '0'
        sign = 1 if integer > 0 else -1
        alphanum = string.digits + string.ascii_lowercase
        nums = alphanum[:base]
        res = ''
        integer *= sign
        while integer:
                integer, mod = divmod(integer, base)
                res += nums[mod]
        return ('' if sign == 1 else '-') + res[::-1]


>>> int2base(-15645, 23)
'-16d5'
>>> int2base(213, 21)
'a3'

Exception from HRESULT: 0x800A03EC Error

I got the same error whilst using Excel 2003 DLLs and trying to write to the 257th column. Excel 2003 limits maximum column per worksheet to 256, thus raising this exception.

For detailed limitations of Excel 2003, see http://office.microsoft.com/en-001/excel-help/excel-specifications-and-limits-HP005199291.aspx

Starting from Excel 2007, column limitation is increased to 16384 columns, see http://office.microsoft.com/en-001/excel-help/excel-specifications-and-limits-HP010073849.aspx

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I would simply delete from schema_version the migration/s that deviates from migrations to be applied. This way you don't throw away any test data that you might have.

For example:

SELECT * from schema_version order by installed_on desc

V_005_five.sql
V_004_four.sql
V_003_three.sql
V_002_two.sql
V_001_one.sql

Migrations to be applied

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Solution here is to delete from schema_version

V_005_five.sql
V_004_four.sql

AND revert any database changes caused. for example if schema created new table then you must drop that table before you run you migrations.

when you run flyway it will only re apply

V_005_five.sql
* V_004_addUserTable.sql *

new schema_version will be

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Hope it helps

How to create a file name with the current date & time in Python?

import datetime

def print_time():
    parser = datetime.datetime.now() 
    return parser.strftime("%d-%m-%Y %H:%M:%S")

print(print_time())

# Output>
# 03-02-2021 22:39:28

Scanner vs. StringTokenizer vs. String.Split

Let's start by eliminating StringTokenizer. It is getting old and doesn't even support regular expressions. Its documentation states:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

So let's throw it out right away. That leaves split() and Scanner. What's the difference between them?

For one thing, split() simply returns an array, which makes it easy to use a foreach loop:

for (String token : input.split("\\s+") { ... }

Scanner is built more like a stream:

while (myScanner.hasNext()) {
    String token = myScanner.next();
    ...
}

or

while (myScanner.hasNextDouble()) {
    double token = myScanner.nextDouble();
    ...
}

(It has a rather large API, so don't think that it's always restricted to such simple things.)

This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse.

Personally, the only time I can remember using Scanner is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a String that I want to split up, it's almost a no-brainer to go with split().

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Is it possible to declare a variable in Gradle usable in Java?

Example using system properties, set in build.gradle, read from Java application (following up from question in comments):

Basically, using the test task in build.gradle, with test task method systemProperty setting a system property that's passed at runtime:

apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'

repositories {
    mavenCentral()
    // mavenLocal()
    // maven { url 'http://localhost/nexus/content/groups/public'; }
}

dependencies {
    testCompile 'junit:junit:4.8.2'
    compile 'ch.qos.logback:logback-classic:1.1.2'
}

test {
  logger.info '==test=='
  systemProperty 'MY-VAR1', 'VALUE-TEST'
}

And here's the rest of the sample code (which you could probably infer, but is included here anyway): it gets a system property MY-VAR1, expected at run-time to be set to VALUE-TEST:

package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  static final Logger log=LoggerFactory.getLogger(HelloWorld.class);
  public static void main(String args[]) {
    log.info("entering main...");
    final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
    System.out.println("(main.out) hello, world: " + val);
    log.info("main.log) MY-VAR1=" + val);
  }
}

Testcase: if MY-VAR is unset, the test should fail:

package example;
...
public class HelloWorldTest {
    static final Logger log=LoggerFactory.getLogger(HelloWorldTest.class);
    @Test public void testEnv() {
        HelloWorld.main(new String[]{});
        final String val = System.getProperty("MY-VAR1", "UNSET (TEST)");
        System.out.println("(test.out) var1=" + val);
        log.info("(test.log) MY-VAR1=" + val);
        assertEquals("env MY-VAR1 set.", "VALUE-TEST", val);
    }
}

Run (note: test is passing):

$ gradle cleanTest test
:cleanTest
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test

BUILD SUCCESSFUL

I've found that the tricky part is actually getting the output from gradle... So, logging is configured here (slf4j+logback), and the log file shows the results (alternatively, run gradle --info cleanTest test; there are also properties that get stdout to the console, but, you know, why):

$ cat app.log
INFO Test worker example.HelloWorld - entering main...
INFO Test worker example.HelloWorld - main.log) MY-VAR1=VALUE-TEST
INFO Test worker example.HelloWorldTest - (test.log) MY-VAR1=VALUE-TEST

If you comment out "systemProperty..." (which, btw, only works in a test task), then:

example.HelloWorldTest > testEnv FAILED
    org.junit.ComparisonFailure at HelloWorldTest.java:14

For completeness, here is the logback config (src/test/resources/logback-test.xml):

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>app.log</file>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d %p %t %c - %m%n</pattern>
        </layout>
 </appender>
 <root level="info">
     <appender-ref ref="FILE"/>
</root>
</configuration> 

Files:

  • build.gradle
  • src/main/java/example/HelloWorld.java
  • src/test/java/example/HelloWorldTest.java
  • src/test/resources/logback-test.xml

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

What MIME type should I use for CSV?

RFC 7111

There is an RFC which covers it and says to use text/csv.

This RFC updates RFC 4180.


Excel

Recently I discovered an explicit mimetype for Excel application/vnd.ms-excel. It was registered with IANA in '96. Note the concerns raised about being at the mercy of the sender and having your machine violated.

Media Type: application/vnd.ms-excel

Name Microsoft Excel (tm)

Required parameters: None

Optional parameters: name

Encoding considerations: base64 preferred

Security considerations: As with most application types this data is intended for interpretation by a program that understands the data on the recipient's system. Recipients need to understand that they are at the "mercy" of the sender, when receiving this type of data, since data will be executed on their system, and the security of their machines can be violated.

OID { org-id ms-files(4) ms-excel (3) }

Object type spreadsheet

Comments This Media Type/OID is used to identify Microsoft Excel generically (i.e., independent of version, subtype, or platform format).

I wasn't aware that vendor extensions were allowed. Check out this answer to find out more - thanks starbeamrainbowlabs for the reference.

How to execute a file within the python interpreter?

I'm trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

Where will log4net create this log file?

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

Can't use SURF, SIFT in OpenCV

The following page provides a relatively good guide that requires few corrections : https://cv-tricks.com/how-to/installation-of-opencv-4-1-0-in-windows-10-from-source/

On step 8, when you are choosing generator for the project (tool used for building), don't forget to specify x64 in the second field if you need it. If you don't, you will get LNK1112 error, which is a linker error caused if one module is created with the x64 compiler, and another module is created with the x86 compiler.

Next, when choosing flags in step 9, don't forget to tick the "OPENCV_ENABLE_NONFREE", and set the path for flag "OPENCV_EXTRA_MODULES_PATH" flag. The path must be set to "modules" folder in opencv-contrib-python.

So you need both opencv, and opencv-contrib-python in order to use SIFT and SURF.

python plot normal distribution

Unutbu answer is correct. But because our mean can be more or less than zero I would still like to change this :

x = np.linspace(-3 * sigma, 3 * sigma, 100)

to this :

x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100)

Modal width (increase)

Simply Use !important after giving width of that class that is override your class.

For Example

.modal .modal-dialog {
  width: 850px !important;
}

Hopefully this will works for you.

How to copy a file to multiple directories using the gnu cp command

I would use cat and tee based on the answers I saw at https://superuser.com/questions/32630/parallel-file-copy-from-single-source-to-multiple-targets instead of cp.

For example:

cat inputfile | tee outfile1 outfile2 > /dev/null

Load properties file in JAR?

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

EDIT: Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

How to save a dictionary to a file?

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

or use context manager, which is better:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

Visual Studio keyboard shortcut to display IntelliSense

Alt + Right Arrow and Alt + Numpad 6 (if Num Lock is disabled) are also possibilities.

How to mock location on device?

If you use this phone only in development lab, there is a chance you can solder away GPS chip and feed serial port directly with NMEA sequences from other device.

How to square all the values in a vector in R?

Try this (faster and simpler):

newData <- data^2

How to display a Windows Form in full screen on top of the taskbar?

FormBorderStyle = FormBorderStyle.Sizable;
TopMost = false;
WindowState = FormWindowState.Normal;

THIS CODE MAKE YOUR WINDOWS FULL SCREEN THIS WILL ALSO COVER WHOLE SCREEN

Spring configure @ResponseBody JSON format

Doesn't answer the question but this is the top google result.

If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation

@JsonInclude(Include.NON_NULL)

on the returning class.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

jQuery rotate/transform

It's because you have a recursive function inside of rotate. It's calling itself again:

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Take that out and it won't keep on running recursively.

I would also suggest just using this function instead:

function rotate($el, degrees) {
    $el.css({
  '-webkit-transform' : 'rotate('+degrees+'deg)',
     '-moz-transform' : 'rotate('+degrees+'deg)',  
      '-ms-transform' : 'rotate('+degrees+'deg)',  
       '-o-transform' : 'rotate('+degrees+'deg)',  
          'transform' : 'rotate('+degrees+'deg)',  
               'zoom' : 1

    });
}

It's much cleaner and will work for the most amount of browsers.

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

How do I force "git pull" to overwrite local files?

I was trying to use the Material2 branch on the Angular2-Webpack-Starter and had a heck of a time. This was the only way I could download and use that branch.

git clone --depth 1 https://github.com/angularclass/angular2-webpack-starter.git

cd angular2-webpack-starter/

git checkout -b material2

Open the project folder and delete all non-hidden files and folders. Leave all the hidden ones.

git add .

git commit -m "pokemon go"

git reset --hard

git pull origin material2

(When the editor pops up, hit ':wq', and then press Enter)

Now you are ready.

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

iOS: Convert UTC NSDate to local Timezone

Here input is a string currentUTCTime (in format 08/30/2012 11:11) converts input time in GMT to system set zone time

//UTC time
NSDateFormatter *utcDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[utcDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[utcDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: 0]];

// utc format
NSDate *dateInUTC = [utcDateFormatter dateFromString: currentUTCTime];

// offset second
NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT];

// format it and send
NSDateFormatter *localDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[localDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[localDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]];

// formatted string
NSString *localDate = [localDateFormatter stringFromDate: dateInUTC];
return localDate;

Change window location Jquery

If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

Use document.location.href to change the page location, place it in the function on a successful ajax run.

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Delete newline in Vim

I would just press A (append to end of line, puts you into insert mode) on the line where you want to remove the newline and then press delete.

Difference Between Cohesion and Coupling

Theory Difference

Cohesion

  • Cohesion is an indication of relative functional strength of module.
  • A cohesive module performs a single task, requiring little interaction with other components in other parts of program.
  • A module having high cohesion and low coupling is said to be functionally independent of other module.

Classification of Cohesion

1.Coincidental 2.Logical 3.Temporal 4.Procedural 5.Communication 6.Sequential 7.Functional

Coupling

  • Coupling is indication of relative interdependence among modules.
  • Degree of coupling between two modules depends on their interface complexity.

Conveniently map between enum and int / String

I found this on the web, it was very helpful and simple to implement. This solution was NOT made by me

http://www.ajaxonomy.com/2007/java/making-the-most-of-java-50-enum-tricks

public enum Status {
 WAITING(0),
 READY(1),
 SKIPPED(-1),
 COMPLETED(5);

 private static final Map<Integer,Status> lookup 
      = new HashMap<Integer,Status>();

 static {
      for(Status s : EnumSet.allOf(Status.class))
           lookup.put(s.getCode(), s);
 }

 private int code;

 private Status(int code) {
      this.code = code;
 }

 public int getCode() { return code; }

 public static Status get(int code) { 
      return lookup.get(code); 
 }

}

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

How to calculate a Mod b in Casio fx-991ES calculator

Here's how I usually do it. For example, to calculate 1717 mod 2:

  • Take 1717 / 2. The answer is 858.5
  • Now take 858 and multiply it by the mod (2) to get 1716
  • Finally, subtract the original number (1717) minus the number you got from the previous step (1716) -- 1717-1716=1.

So 1717 mod 2 is 1.

To sum this up all you have to do is multiply the numbers before the decimal point with the mod then subtract it from the original number.

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Setting the height of a SELECT in IE

you can use a combination of font-size and line-height to force it to go larger, but obviously only in the situations where you need the font larger too

edit:

Example -> http://www.bse.co.nz EDIT: (this link is no longer relevant)

the select next to the big search box has the following css rules:

#navigation #search .locationDrop {
    font-size:2em;
    line-height:27px;
    display:block;
    float:left;
    height:27px;
    width:200px;
}

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

How to set a Javascript object values dynamically?

myObj[prop] = value;

That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.

How to remove hashbang from url?

window.router = new VueRouter({
   hashbang: false,
   //abstract: true,
  history: true,
    mode: 'html5',
  linkActiveClass: 'active',
  transitionOnLoad: true,
  root: '/'
});

and server is properly configured In apache you should write the url rewrite

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

How can I throw CHECKED exceptions from inside Java 8 streams?

You cannot.

However, you may want to have a look at one of my projects which allows you to more easily manipulate such "throwing lambdas".

In your case, you would be able to do that:

import static com.github.fge.lambdas.functions.Functions.wrap;

final ThrowingFunction<String, Class<?>> f = wrap(Class::forName);

List<Class> classes =
    Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
          .map(f.orThrow(MyException.class))
          .collect(Collectors.toList());

and catch MyException.

That is one example. Another example is that you could .orReturn() some default value.

Note that this is STILL a work in progress, more is to come. Better names, more features etc.

Maximum on http header values?

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5. Various ad hoc limitations on individual header field length are found in practice, often depending on the specific field semantics.

HTTP Header values are restricted by server implementations. Http specification doesn't restrict header size.

A server that receives a request header field, or set of fields, larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code. Ignoring such header fields would increase the server's vulnerability to request smuggling attacks (Section 9.5).

Most servers will return 413 Entity Too Large or appropriate 4xx error when this happens.

A client MAY discard or truncate received header fields that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics.

Uncapped HTTP header size keeps the server exposed to attacks and can bring down its capacity to serve organic traffic.

Source

Installation of SQL Server Business Intelligence Development Studio

It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.

BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.

EDIT

This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).

MSBUILD : error MSB1008: Only one project can be specified

I did use solution given in https://www.codingdefined.com/2014/10/solved-msbuild-error-msb1008-only-one.html and that solves the issue. All we need to do is check spaces and ''(check backslashes) in the command

How to Convert an int to a String?

You have two options:

1) Using String.valueOf() method:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2) adding an empty string:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

Casting is not an option, will throw a ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!

How do I get HTTP Request body content in Laravel?

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

From the docs:

$this->call($method, $uri, $parameters, $files, $server, $content);

Builder Pattern in Effective Java

This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.

NutritionalFacts n = new NutritionalFacts()

Builder b = new n.Builder(10).carbo(23).fat(1).build();

Nested Classes

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

What is the correct way to check for string equality in JavaScript?

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

Is it possible to embed animated GIFs in PDFs?

Having the ability to add small animations to a PDF (portable document format, independent of application software, hardware, and operating systems) would make it the perfect solution for making extremely useful user guides. Some text, some images, and some animations/videos, all in one file that can be read by anybody on any computer.

As of acrobat pro version x, a gif can be added under Tools > Insert from File. But the gif wont play, it only shows the first image.

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.DropDownListFor how to set default value

I hope this is helpful to you.

Please try this code,

 @Html.DropDownListFor(model => model.Items, new List<SelectListItem>
   { new SelectListItem{Text="Deactive", Value="False"},
     new SelectListItem{Text="Active", Value="True",  Selected = true},
     })

CORS header 'Access-Control-Allow-Origin' missing

in your ajax request, adding:

dataType: "jsonp",

after line :

type: 'GET',

should solve this problem ..

hope this help you

How can I split a text into sentences?

You can also use sentence tokenization function in NLTK:

from nltk.tokenize import sent_tokenize
sentence = "As the most quoted English writer Shakespeare has more than his share of famous quotes.  Some Shakespare famous quotes are known for their beauty, some for their everyday truths and some for their wisdom. We often talk about Shakespeare’s quotes as things the wise Bard is saying to us but, we should remember that some of his wisest words are spoken by his biggest fools. For example, both ‘neither a borrower nor a lender be,’ and ‘to thine own self be true’ are from the foolish, garrulous and quite disreputable Polonius in Hamlet."

sent_tokenize(sentence)

What JSON library to use in Scala?

@AlaxDean's #7 answer, Argonaut is the only one that I was able to get working quickly with sbt and intellij. Actually json4s also took little time but dealing with a raw AST is not what I wanted. I got argonaut to work by putting in a single line into my build.st:

libraryDependencies += "io.argonaut" %% "argonaut" % "6.0.1"

And then a simple test to see if it I could get JSON:

package mytest


import scalaz._, Scalaz._
import argonaut._, Argonaut._

object Mytest extends App {

  val requestJson  =
    """
    {
      "userid": "1"
    }
    """.stripMargin

  val updatedJson: Option[Json] = for {
    parsed <- requestJson.parseOption
  } yield ("name", jString("testuser")) ->: parsed

  val obj = updatedJson.get.obj
  printf("Updated user: %s\n", updatedJson.toString())
  printf("obj : %s\n", obj.toString())
  printf("userid: %s\n", obj.get.toMap("userid"))
}

And then

$ sbt
> run
Updated user: Some({"userid":"1","name":"testuser"})
obj : Some(object[("userid","1"),("name","testuser")])
userid: "1"

Make sure you are familiar with Option which is just a value that can also be null (null safe I guess). Argonaut makes use of Scalaz so if you see something you don't understand like the symbol \/ (an or operation) it's probably Scalaz.

Jupyter/IPython Notebooks: Shortcut for "run all"?

As of 5.5 you can run Kernel > Restart and Run All

Oracle - how to remove white spaces?

REPLACE(REPLACE(a.CUST_ADDRESS1,CHR(10),' '),CHR(13),' ') as ADDRESS

What version of javac built my jar?

One liner (Linux)

unzip -p mylib.jar META-INF/MANIFEST.MF

This prints the content of MANIFEST.MF file to stdout (hopefully there is one in your jar file :)

Depending on what built your package, you will find the JDK version in Created-By or Build-Jdk key.

How can I check if mysql is installed on ubuntu?

Multiple ways of searching for the program.

Type mysql in your terminal, see the result.

Search the /usr/bin, /bin directories for the binary.

Type apt-cache show mysql to see if it is installed

locate mysql

From io.Reader to string in Go

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

How to locate the Path of the current project directory in Java (IDE)?

File currDir = new File(".");
String path = currDir.getAbsolutePath();
System.out.println(path);

This will print . at the end. To remove, simply truncate the string by one char e.g.:

File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
System.out.println(path);

Make header and footer files to be included in multiple html pages

You can accomplish this with jquery.

Place this code in index.html

<html>
<head>
<title></title>
<script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous">
</script>
<script> 
$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>

and put this code in header.html and footer.html, at the same location as index.html

<a href="http://www.google.com">click here for google</a>

Now, when you visit index.html, you should be able to click the link tags.

Secondary axis with twinx(): how to add to legend?

I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Find text string using jQuery?

Take a look at highlight (jQuery plugin).

How do you import an Eclipse project into Android Studio now?

Android Studio has been improved since this question was posted, and the latest versions of Android Studio (as of this writing, we are at 2.1.1) have fairly good Eclipse importing capabilities, so importing Eclipse projects directly into Android Studio is now the best approach for migrating projects from Eclipse into Android Studio.

I will describe how to do this below, including a few of the pitfalls that one might encounter. I will deal in particular with importing an Eclipse workspace that contains multiple apps sharing one or more project libraries (the approaches posted thus far seem limited to importing just one Eclipse app project and its project libraries). While I don't deal with every possible issue, I do go into a lot of detail regarding some of them, which I hope will be helpful to those going through this process for the first time themselves.

I recently imported the projects from an Eclipse workspace. This workspace included four library projects that were shared between up to nine projects each.

Some background:

An Eclipse workspace contains multiple projects, which may be library projects or apps.

An Android Studio project is analogous to an Eclipse workspace, in that it can contain both library projects and apps. However, a library project or an app is represented by a "module" in Android Studio, whereas it is represented by a "project" in Eclipse.

So, to summarize: Eclipse workspaces will end up as Android Studio projects, and Eclipse projects inside a workspace will end up as Android Studio modules inside a project.

You should start the import process by creating an Android Studio project (File / New / New Project). You might give this project the same (or similar) name as you gave your Eclipse workspace. This project will eventually hold all of your modules, one each for each Eclipse project (including project libraries) that you will import.

The import process does not change your original Eclipse files, so long as you place the imported files in a different folder hierarchy, so you should choose a folder for this project that is not in your original Eclipse hierarchy. For example, if your Eclipse projects are all in a folder called Android, you might create a sibling folder called AStudio.

Your Android Studio project can then be created as a sub-folder of this new folder. The New Project wizard will prompt you to enter this top-level project folder, into which it will create your project.

Android Studio's new project wizard will then ask you to configure a single module at the time you create the project. This can be a little confusing at first, because they never actually tell you that you are creating a module, but you are; you are creating a project with a single module in it. Apparently, every project is required to have at least one module, so, since you are relying on Eclipse to provide your modules, your initial module will be a placeholder to vacuously satisfy that formal requirement.

Thus, you probably will want to create an initial module for your project that does as little as possible. Therefore, select Phone and Tablet as the type of your module, accept the default minimum SDK (API level 8), and select Add No Activity for your module.

Next, select one of the Eclipse app projects in your workspace that requires the largest number of libraries as your first project to import. The advantage of doing this is that when you import that project, all the library projects that it uses (directly, or indirectly, if some of your library projects themselves require other library projects) will get imported along with it as part of the importing process.

Each of these imported projects will get its own module within your Android Studio project. All of these modules will be siblings of one another (both in your project hierarchy, and in the folder hierarchy where their files are placed), just as if you had imported the modules separately. However, the dependencies between the modules will be created for you (in your app's build.gradle files) as part of the importing process.

Note that after you finish importing, testing and debugging this "most dependent" Eclipse project and its supporting library projects, you will go on to import a second Eclipse app project (if you have a second one in your workspace) and its library project modules (with those imported earlier getting found by the import wizard as existing modules and re-used for this new module, rather than being duplicated).

So, you should never have to import even a single library project from Eclipse directly; they will all be brought in indirectly, based on their dependencies upon app projects that you import. This is assuming that all of your library projects in the workspace are created to serve the needs of one or more app projects in that same workspace.

To perform the import of this first app project, back in Android Studio, while you are in the project that you just created, select File / New / New Module. You might think that you should be using File / New / Import Module, but no, you should not, because if you do that, Android Studio will create a new project to hold your imported module, and it will import your module to that project. You actually could create your first module that way, but then the second through Nth modules would still require that you use this other method (for importing a module into an existing project), and so I think that just starting with an "empty" project (or rather, one with its own vacuous, do-nothing placeholder module), and then importing each of your Eclipse projects as a new module into that project (i.e., the approach we are taking here), may be less confusing.

So, you are going to take your practically-empty new project, and perform a File / New / New Module in it. The wizard that this invokes will give you a choice of what kind of module you want to create. You must select "Import Eclipse ADT Project." That is what accesses the wizard that knows how to convert an Eclipse project into an Android Studio module (along with the library modules on which it depends) within your current Android Studio project.

When prompted for a source folder, you should enter the folder for your Eclipse project (this is the folder that contains that project's AndroidManifest.xml file).

The import wizard will then display the module name that it intends to create (similar to your original Eclipse project's name, but with a lower-case first letter because that is a convention that distinguishes module names from project names (which start with an upper-case letter). It usually works pretty well to accept this default.

Below the module name is a section titled "Additional required modules." This will list every library required by the module you are importing (or by any of its libraries, etc.). Since this is the first module you are importing, none of these will already be in your project, so each of them will have its Import box checked by default. You should leave these checked because you need these modules. (Note that when you import later Eclipse app projects, if a library that they need has already been imported, those libraries will still appear here, but there will be a note that "Project already contains module with this name," and the Import box will be un-checked by default. In that case, you should leave the box unchecked, so that the importer will hook up your newly-imported module(s) to the libraries that have already been imported. It may be that accepting the default names that Android Studio creates for your modules will be important for allowing the IDE to find and re-use these library modules.

Next, the importer will offer to replace any jars and library sources with Gradle dependencies, and to create camelCase module names for any dependent modules, checking all those options by default. You should generally leave these options checked and continue. Read the warning, though, about possible problems. Remember that you can always delete an imported module or modules (via the Project Structure dialog) and start the import process over again.

The next display that I got (YMMV) claims that the Android Support Repository is not installed in my SDK installation. It provides a button to open the Android SDK Manager for purposes of installing it. However, that button did not work for me. I manually opened the SDK manager as a separate app, and found that the Android Support Repository was already installed. There was an update, however. I installed that, and tapped the Refresh button in the import dialog, but that did nothing. So, I proceeded, and the perceived lack of this Repository did not seem to hurt the importing process (although I did get messages regarding it being missing from time to time later on, while working with the imported code, which I was able to appease by clicking a supplied link that corrected the problem - at least temporarily). Eventually this problem went away when I installed an update to the repository, so you may not experience it at all.

At this point, you will click Finish, and after a bit it should create your modules and build them. If all goes well, you should get a BUILD SUCCESSFUL message in your Gradle Console.

One quirk is that if the build fails, you may not see your imported modules in the Project hierarchy. It seems that you need to get to the first valid build before the new modules will appear there (my experience, anyway). You may still be able to see the new modules in the File / Project Structure dialog (e.g., if you want to delete them and start your import over).

Remember that since you are not changing your original Eclipse projects, you can always delete the modules that you have just imported (if importing goes badly), and start all over again. You can even make changes to the Eclipse side after deleting your Android Studio modules, if that will make importing go better the second time (so long as you preserve your fallback ability to build your existing source under Eclipse). As you'll see when we discuss version control below, it may be necessary for you to retain your ability to build under Eclipse, because the project structure is changed under Android Studio, so if you need to go back to a commit that precedes your move to Android Studio (e.g., to make a bug fix), you will want to have the ability to build that earlier commit in Eclipse.

To delete a module, you must select File / Project Structure, then select the module from the left side of the dialog, and then hit the delete key. For some reason, I was not able to delete a module directly in the Project hierarchy; it had to be done using this Project Structure dialog.

The import wizard generates an import-summary.txt file containing a detailed list of any issues it may have encountered, along with actions taken to resolve them. You should read it carefully, as it may provide clues as to what is happening if you have trouble building or running the imported code. It will also help you to find things that the importer moves around to accommodate the different structure of Android Studio projects.

If all does not go well, then have at look at these possible problems that you may encounter, along with solutions for those problems:

Generally speaking, there are two main kinds of problems that I encountered:

  1. Proguard problems
  2. Manifest problems

When Proguard is messed up, the (obfuscated) names of methods in your libraries may not match the names being used to invoke them from your app, and you will get compiler errors like "error: cannot find symbol class ..."

In Eclipse, Proguard stuff is pretty much ignored for library projects, with the Proguard stuff for any app project that you are building determining the obfuscation, etc. for not just itself, but for processing all of the libraries on which it depends. And that is generally what you want.

In Android Studio, however, you need to make some changes to attain this same effect. Basically, in the build.gradle files for each of your library project modules, you will want something like this:

buildTypes {
    release {
        minifyEnabled false
        consumerProguardFiles 'proguard.cfg'
    }
}

Where proguard.cfg is your library module's own proguard configuration file.

The term "consumer" in "consumerProguardFiles" apparently refers to the app module that is using this library module. So the proguard commands from that app are used in preference to those of the library module itself, and apparently this results in obfuscations that are coordinated and compatible, so that all calls from the app module to its library modules are made with matching symbols.

These "consumerProguardFiles" entries are not created automatically during the import process (at least that was my own experience) so you will want to make sure to edit that into your library modules' build.gradle files if they are not created for you during importing.

If you wanted to distribute your library projects separately, with obfuscation, then you would need an individual proguard file for them; I have not done this myself, and so that is beyond the scope of this answer.

In the app module, you will want something like this:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles 'proguard.cfg'
    }
}

(BTW, as of this writing, while my apps are running just fine, I have not yet directly confirmed that things are actually getting obfuscated using this approach, so do check this yourself - e.g., by using a decompiler like apktool. I will be checking this later on, and will edit this answer when I get that info).

The second kind of problem is due to the fact that Eclipse pretty much ignores the manifest files for library projects when compiling an app project that uses those library projects, while in Android Studio, there is an interleaving of the two that apparently does not consistently prioritize the app's manifest over those of its libraries.

I encountered this because I had a library manifest that listed (just for documentation purposes) an abstract Activity class as the main activity. There was a class derived from this abstract class in my app that was declared in the manifest of each app that used the library.

In Eclipse, this never caused any problems, because the library manifests were ignored. But in Android Studio, I ended up with that abstract class as my activity class for the app, which caused a run-time error when the code made an attempt to instantiate that abstract class.

You have two choices in this case:

  1. Use tools syntax to override specific library manifest stuff in your app manifest - for example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.goalstate.WordGames.FullBoard.trialsuite"
       xmlns:tools="http://schemas.android.com/tools"
       .
       .
        <application
           tools:replace="android:name"

or,

  1. Strip out practically everything from your library modules' manifests, and rely upon the app module's manifest to provide every value. Note that you do need to have a manifest for each library module, but not much more is required than the header and a bare manifest element with just a package attribute in it.

I tried both and ended up with approach 2., above, as the simpler method. However, if you wanted to distribute your library modules separately, you would need to create a more meaningful manifest file that reflects each library module's own individual requirements.

There is probably a more "correct" way to do this which puts requirements (e.g., permissions) for each library in the library manifest itself, and allows the automatic interleaving process to combine these with those declared for the app. However, given that Eclipse ignores the manifests for libraries, it seems safer at least initially to rely entirely on the app manifests and just strip the library manifests down to the bare bones.

Be aware that some of the project properties, and also the manifest attributes, from your Eclipse project will have been used to construct portions of your build.gradle files. Specifically, your compileSdkVersion in build.gradle is set to the project build version from the Eclipse project properties, applicationId is the package name from your app's manifest, and minSdkVersion and targetSdkVersion are also copied from the app's manifest file. The dependencies section of build.gradle comes from the library project dependencies in your project's properties.

Note that this may make some of your AndroidManifest.xml values redundant and quite possibly residual (i.e., unused). This could create confusion. My understanding is that the build.gradle values are the ones that actually have an effect, and that the manifest values like targetSdkVersion are not used any more for purposes of building. However, they may still be used by app stores such as Google Play; I don't know for certain one way or the other, so at this point I am just maintaining them in tandem.

Besides the above two kinds of issue, there are more routine things like importing a project that has a project build level of 22 when you have only installed SDK level 23 in Android Studio. In that situation, it is probably better to edit your app module's build.gradle file to move compileSdkVersion from 22 (the imported value) to 23, than it would be to install the SDK for level 22, but either approach should work.

Throughout this entire process, when something does not build properly and you make a change to try to address it, you might want to try Build / Rebuild Project and/or Tools / Android / Sync Project with Gradle Files, and/or File / Invalidate Caches/Restart, to make sure that your changes have been fully incorporated. I don't know exactly when these are truly necessary, because I don't know how much is done incrementally when you haven't yet had a successful build, but I performed them all fairly regularly as a kind of superstitious ritual, and I'm fairly certain that it helped. For example, when I got a Resources$NotFound runtime error that appeared to be from an inability to find the launch icon resource, I tried all three, and the problem was fixed.

When you have performed the above for your first Eclipse project and have attained a successful build, then with luck, you can select your app module from the dropdown at the top of the Android Studio display to the left of the play button, then click the play button itself, then select a device or Android Virtual Device, and the app should be loaded for running.

Likewise, you should be able to create a signed copy of your app using the Build / Generate Signed APK feature. Note that some import-related errors may appear when running your signed copy that do not appear when using the play button, so you need to confirm that both are working before deciding that your import is complete.

Following this, you will probably want to turn on version control. I am using git myself, but there are a number of other options available.

Version control is mostly beyond the scope of this answer, but there are a few things that are affected by the importing process. First, in Eclipse you might have your various projects in various folders stuck all over the place, but when you import into Android Studio, all modules will be created as direct child folders of your main project folder. So if you had a separate git folder for each project in Eclipse, or for related groups of projects organized under a parent folder for each group (as I did), that is not going to translate very well to Android Studio.

My knowledge of this is limited as I have not worked with version control yet in Android Studio, so maybe there is a way around this, but it appears that all version control in Android Studio is unified at the project level, and so all of your modules will be under a single git archive.

This means that you may need to abandon your old git archive and start fresh with a new archive for your imported source code. And that means that you will want to keep your old git archive around, so that it can be used with Eclipse to perform any needed bug fixes, etc., at least for a while. And you also will want it to preserve a history of your project.

If you are fortunate enough to have had all of your projects organized under a single Eclipse workspace, and if you were using a single git archive for those projects, then it is possible that you might just copy your old git archive from in and under your Eclipse workspace folder to in and under your Android Studio project folder. Then, you could edit any still-relevant .gitignore items from you Eclipse project into the auto-generated .gitignore file for your Android Studio project, and let git figure out what has been changed during the importing process (and some things will have been moved around - for example, the manifest file is no longer at the top level of your module). Others have reported that git is pretty good at figuring out what has changed; I have not tried this myself.

But even if you did this, going back to a commit that precedes your move from Eclipse to Android Studio would be going back to a set of files that would only make sense from inside Eclipse. So it sounds, well, "difficult" to work with. Especially since Eclipse will still be pointing to its original set of project folders.

I personally had multiple git archives for my various sets of related projects, and so I decided to just make a clean break and start git over again in Android Studio. If you had to do this, it could affect your planning, because you would want to be at a very stable point in your code development before making the move in that case, since you will lose some accessibility to that older code within your version control system (e.g., ability to merge with post-import code) once you have made the move to Android Studio.

The part of this answer that pertains to git is partly speculative, since I have not actually worked with version control yet on my imported project files, but I wanted to include it to give some idea of the challenges, and I plan to update my answer after I have worked more with version control inside Android Studio.

Only on Firefox "Loading failed for the <script> with source"

I just had the same issue on an application that is loading a script with a relative path.

It appeared the script was simply blocked by Adblock Plus.

Try to disable your ad/script blocker (Adblock, uBlock Origin, Privacy Badger…) or relocate the script such that it does not match your ad blocker's rules.

If you don't have such a plugin installed, try to reproduce the issue while running Firefox in safe mode.

  • If you cannot reproduce it in safe mode, it means your issue is linked to one of your plugins or settings.
  • Otherwise, it might be a different issue. Make sure you have the same error message as in the question. Also look at the network tab of the developer tools to check if your script is listed (reload the page first if needed).

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

Here is my solution which is further refined from one posted by @john-magnolia and solves some of its issues

/**
 * Toggle on/off arrow for Twitter Bootstrap collapsibles.
 *
 * Multi-collapsible-friendly; supports several collapsibles in the same group, on the same page.
 */
function animateCollapsibles() {

    $('.collapse').on('show', function() {
        var $t = $(this);
        var header = $("a[href='#" + $t.attr("id") + "']");
        header.find(".icon-chevron-right").removeClass("icon-chevron-right").addClass("icon-chevron-down");
    }).on('hide', function(){
        var $t = $(this);
        var header = $("a[href='#" + $t.attr("id") + "']");
        header.find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-right");
    });
}

And here is the example markup:

<div class="accordion" id="accordion-send">
    <div class="accordion-group">
        <div class="accordion-heading">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
                <i class="icon icon-chevron-right"></i> Send notice
            </a>
        </div>
        <div id="collapse-refund" class="accordion-body collapse">
            <div class="accordion-inner">
                <p>Lorem ipsum Toholampi city</p>
            </div>
        </div>
    </div>
</div>

form with no action and where enter does not reload page

You'll want to include action="javascript:void(0);" to your form to prevent page reloads and maintain HTML standard.

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

Is std::vector copying the objects with a push_back?

From C++11 onwards, all the standard containers (std::vector, std::map, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:

// Example object class.
class object
{
private:
    int             m_val1;
    std::string     m_val2;

public:
    // Constructor for object class.
    object(int val1, std::string &&val2) :
        m_val1(val1),
        m_val2(std::move(val2))
    {

    }
};

std::vector<object> myList;

// #1 Copy into the vector.
object foo1(1, "foo");
myList.push_back(foo1);

// #2 Move into the vector (no copy).
object foo2(1024, "bar");
myList.push_back(std::move(foo2));

// #3 Move temporary into vector (no copy).
myList.push_back(object(453, "baz"));

// #4 Create instance of object directly inside the vector (no copy, no move).
myList.emplace_back(453, "qux");

Alternatively you can use various smart pointers to get mostly the same effect:

std::unique_ptr example

std::vector<std::unique_ptr<object>> myPtrList;

// #5a unique_ptr can only ever be moved.
auto pFoo = std::make_unique<object>(1, "foo");
myPtrList.push_back(std::move(pFoo));

// #5b unique_ptr can only ever be moved.
myPtrList.push_back(std::make_unique<object>(1, "foo"));

std::shared_ptr example

std::vector<std::shared_ptr<object>> objectPtrList2;

// #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
// value and the local copy simultaneously.
auto pFooShared = std::make_shared<object>(1, "foo");
objectPtrList2.push_back(pFooShared);
// Pointer to object stored in the vector, but pFooShared is still valid.

Can't import org.apache.http.HttpResponse in Android Studio

According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

RecyclerView - How to smooth scroll to top of item on a certain position?

Thanks, @droidev for the solution. If anyone looking for Kotlin solution, refer this:

    class LinearLayoutManagerWithSmoothScroller: LinearLayoutManager {
    constructor(context: Context) : this(context, VERTICAL,false)
    constructor(context: Context, orientation: Int, reverseValue: Boolean) : super(context, orientation, reverseValue)

    override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
        super.smoothScrollToPosition(recyclerView, state, position)
        val smoothScroller = TopSnappedSmoothScroller(recyclerView?.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private class TopSnappedSmoothScroller(context: Context?) : LinearSmoothScroller(context){
        var mContext = context
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
            return LinearLayoutManagerWithSmoothScroller(mContext as Context)
                    .computeScrollVectorForPosition(targetPosition)
        }

        override fun getVerticalSnapPreference(): Int {
            return SNAP_TO_START
        }


    }

}

Centering a Twitter Bootstrap button

.span7.btn { display: block;   margin-left: auto;   margin-right: auto; }

I am not completely familiar with bootstrap, but something like the above should do the trick. It may not be necessary to include all of the classes. This should center the button within its parent, the span7.

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

How to get a cross-origin resource sharing (CORS) post request working

I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.

        var xhr = new XMLHttpRequest()
        xhr.open('POST', 'https://mywebsite.com', true)
        xhr.withCredentials = true
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 2) {// do something}
        }
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(json)

Hopefully this helps anyone else with the same issues.

DataGrid get selected rows' column values

DataGrid get selected rows' column values it can be access by below code. Here grid1 is name of Gride.

private void Edit_Click(object sender, RoutedEventArgs e)
{
    DataRowView rowview = grid1.SelectedItem as DataRowView;
    string id = rowview.Row[0].ToString();
}

What does %5B and %5D in POST requests stand for?

[] is replaced by %5B%5D at URL encoding time.

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Generate random int value from 3 to 6

You can do this:

DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

SELECT CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)

And that was taken directly from this link, I don't really know how to give proper credit for this answer.

How do I refresh the page in ASP.NET? (Let it reload itself by code)

If you don't want to do a full page refresh, then how about wrapping what you want to refresh inside of a UpdatePanel and then do an asynchronous postback?

How to check type of variable in Java?

I did it using: if(x.getClass() == MyClass.class){...}

Android map v2 zoom to show all the markers

Google Map V2

The following solution works for Android Marshmallow 6 (API 23, API 24, API 25, API 26, API 27, API 28). It also works in Xamarin.

LatLngBounds.Builder builder = new LatLngBounds.Builder();

//the include method will calculate the min and max bound.
builder.include(marker1.getPosition());
builder.include(marker2.getPosition());
builder.include(marker3.getPosition());
builder.include(marker4.getPosition());

LatLngBounds bounds = builder.build();

int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen

CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

mMap.animateCamera(cu);

How to print Unicode character in Python?

To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2.x, you also need to prefix the string literal with 'u'.

Here's an example running in the Python 2.x interactive console:

>>> print u'\u0420\u043e\u0441\u0441\u0438\u044f'
??????

In Python 2, prefixing a string with 'u' declares them as Unicode-type variables, as described in the Python Unicode documentation.

In Python 3, the 'u' prefix is now optional:

>>> print('\u0420\u043e\u0441\u0441\u0438\u044f')
??????

If running the above commands doesn't display the text correctly for you, perhaps your terminal isn't capable of displaying Unicode characters.

These examples use Unicode escapes (\u...), which allows you to print Unicode characters while keeping your source code as plain ASCII. This can help when working with the same source code on different systems. You can also use Unicode characters directly in your Python source code (e.g. print u'??????' in Python 2), if you are confident all your systems handle Unicode files properly.

For information about reading Unicode data from a file, see this answer:

Character reading from file in Python

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT (column1), column2
FROM table1
GROUP BY column1

How to implement a Map with multiple keys?

Proposal, as suggested by some answerers:

public interface IDualMap<K1, K2, V> {

    /**
    * @return Unmodifiable version of underlying map1
    */
    Map<K1, V> getMap1();

    /**
    * @return Unmodifiable version of underlying map2
    */
    Map<K2, V> getMap2();

    void put(K1 key1, K2 key2, V value);

}

public final class DualMap<K1, K2, V>
        implements IDualMap<K1, K2, V> {

    private final Map<K1, V> map1 = new HashMap<K1, V>();

    private final Map<K2, V> map2 = new HashMap<K2, V>();

    @Override
    public Map<K1, V> getMap1() {
        return Collections.unmodifiableMap(map1);
    }

    @Override
    public Map<K2, V> getMap2() {
        return Collections.unmodifiableMap(map2);
    }

    @Override
    public void put(K1 key1, K2 key2, V value) {
        map1.put(key1, value);
        map2.put(key2, value);
    }
}