Programs & Examples On #Jprofiler

JProfiler is a commercially licensed Java profiling tool developed by ej-technologies GmbH targeted at Java EE and Java SE applications.

How to find a Java Memory Leak

NetBeans has a built-in profiler.

Laravel Blade html image

in my case this worked perfectly

<img  style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">

this code is used to display image from folder

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.

sudo find / -name "libopencv_core.so.2.4*"

Then I got the result:

 /usr/local/lib/libopencv_core.so.2.4.

Create a file called /etc/ld.so.conf.d/opencv.conf and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/ to my opencv.conf file. Run the command line as follows.

sudo ldconfig -v

Try to run the command again.

How to generate service reference with only physical wsdl file

There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.

1. To create it via the IDE:

In the solution explorer pane, right click on the project that you would like to add the Service to:

enter image description here

Then, you can enter the path to your service WSDL and hit go:

enter image description here

2. To create it via the command line:

Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:

WSDL /verbose C:\path\to\wsdl

WSDL.exe will then output a .cs file for your consumption.

If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:

WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd

If you need VB output, use /language:VB in addition to the /verbose.

java.lang.ClassNotFoundException: org.apache.log4j.Level

You also need to include the Log4J JAR file in the classpath.

Note that slf4j-log4j12-1.6.4.jar is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.

TypeError: no implicit conversion of Symbol into Integer

myHash.each{|item|..} is returning you array object for item iterative variable like the following :--

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

You should do this:--

def format
  output = Hash.new
  myHash.each do |k, v|
    output[k] = cleanup(v)
  end
  output
end

Save PL/pgSQL output from PostgreSQL to a CSV file

New version - psql 12 - will support --csv.

psql - devel

--csv

Switches to CSV (Comma-Separated Values) output mode. This is equivalent to \pset format csv.


csv_fieldsep

Specifies the field separator to be used in CSV output format. If the separator character appears in a field's value, that field is output within double quotes, following standard CSV rules. The default is a comma.

Usage:

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv  postgres

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv -P csv_fieldsep='^'  postgres

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv  postgres > output.csv

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

How to fix 'sudo: no tty present and no askpass program specified' error?

1 open /etc/sudoers

type sudo vi /etc/sudoers. This will open your file in edit mode.

2 Add/Modify linux user

Look for the entry for Linux user. Modify as below if found or add a new line.

<USERNAME> ALL=(ALL) NOPASSWD: ALL

3 Save and Exit from edit mode

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

How to Troubleshoot Intermittent SQL Timeout Errors

Are these servers virtualized? On another post I've read about a SQL server running sometimes very slowly because of lack of sufficient memory. This in turn was caused by a so-called memory balloon that the virtualizer used to limit the amount of memory used by that virtual server. It was hard to find because the pressure on physical memory had nothing to do with the SQL server itself.

Another common cause for a temporary performance degradation might be a virus scanner. When a new virus definition is installed, all other processes will suffer and run very slow. Check out any other automatic update process, this might also take a lot of resources quite unexpectedly. Good luck with it!

How to set image button backgroundimage for different state?

if you want pressed image button then image should be change from normal to pressed

But I best way will be to customize the RadioButton and use them in a group. I have see an example of that. Sorry I did not remember that link.

but if you want to avoid that. You need to add this to your selector.xml

Once Done. Just got to your code and add this

public void onClick ( View v ) {
    myImageButton.setSelected ( true ) ;
 }

You will see the result. But you have to mange the states which button was recently press. So that you can set

  myOLDImageButton.setSelected ( false ) ;

I suggest you to put all button reference in a array.

Unicode character as bullet for list-item in CSS

Today, there is a ::marker option. so,

li::marker {
  content: "\2605";
}

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;

Use JSTL forEach loop's varStatus as an ID

you'd use any of these:

JSTL c:forEach varStatus properties

Property Getter Description

  • current getCurrent() The item (from the collection) for the current round of iteration.

  • index getIndex() The zero-based index for the current round of iteration.

  • count getCount() The one-based count for the current round of iteration

  • first isFirst() Flag indicating whether the current round is the first pass through the iteration
  • last isLast() Flag indicating whether the current round is the last pass through the iteration

  • begin getBegin() The value of the begin attribute

  • end getEnd() The value of the end attribute

  • step getStep() The value of the step attribute

"Cannot start compilation: the output path is not specified for module..."

You have to define a path in the "Project compiler output" field in

File > Project Structure... > Project > Project compiler output

This path will be used to store all project compilation results.

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

javascript date + 7 days

var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();

var output = d.getFullYear() + '/' +
    (month < 10 ? '0' : '') + month + '/' +
    (day < 10 ? '0' : '') + day;

$('#txtEndDate').val(output);

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

How to update/refresh specific item in RecyclerView

I think I have an Idea on how to deal with this. Updating is the same as deleting and replacing at the exact position. So I first remove the item from that position using the code below:

public void removeItem(int position){
    mData.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, mData.size());
}

and then I would add the item at that particular position as shown below:

public void addItem(int position, Landscape landscape){
    mData.add(position, landscape);
    notifyItemInserted(position);
    notifyItemRangeChanged(position, mData.size());
}

I'm trying to implement this now. I would give you a feedback when I'm through!

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

How to slice an array in Bash

Array slicing like in Python (From the rebash library):

array_slice() {
    local __doc__='
    Returns a slice of an array (similar to Python).

    From the Python documentation:
    One way to remember how slices work is to think of the indices as pointing
    between elements, with the left edge of the first character numbered 0.
    Then the right edge of the last element of an array of length n has
    index n, for example:
    ```
    +---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
    -6  -5  -4  -3  -2  -1
    ```

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1:-2 "${a[@]}")
    1 2 3
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0:1 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
    empty
    >>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
    empty

    Slice indices have useful defaults; an omitted first index defaults to
    zero, an omitted second index defaults to the size of the string being
    sliced.
    >>> local a=(0 1 2 3 4 5)
    >>> # from the beginning to position 2 (excluded)
    >>> echo $(array.slice 0:2 "${a[@]}")
    >>> echo $(array.slice :2 "${a[@]}")
    0 1
    0 1

    >>> local a=(0 1 2 3 4 5)
    >>> # from position 3 (included) to the end
    >>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice 3: "${a[@]}")
    3 4 5
    3 4 5

    >>> local a=(0 1 2 3 4 5)
    >>> # from the second-last (included) to the end
    >>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice -2: "${a[@]}")
    4 5
    4 5

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -4:-2 "${a[@]}")
    2 3

    If no range is given, it works like normal array indices.
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -1 "${a[@]}")
    5
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -2 "${a[@]}")
    4
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1 "${a[@]}")
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice 6 "${a[@]}"; echo $?
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice -7 "${a[@]}"; echo $?
    1
    '
    local start end array_length length
    if [[ $1 == *:* ]]; then
        IFS=":"; read -r start end <<<"$1"
        shift
        array_length="$#"
        # defaults
        [ -z "$end" ] && end=$array_length
        [ -z "$start" ] && start=0
        (( start < 0 )) && let "start=(( array_length + start ))"
        (( end < 0 )) && let "end=(( array_length + end ))"
    else
        start="$1"
        shift
        array_length="$#"
        (( start < 0 )) && let "start=(( array_length + start ))"
        let "end=(( start + 1 ))"
    fi
    let "length=(( end - start ))"
    (( start < 0 )) && return 1
    # check bounds
    (( length < 0 )) && return 1
    (( start < 0 )) && return 1
    (( start >= array_length )) && return 1
    # parameters start with $1, so add 1 to $start
    let "start=(( start + 1 ))"
    echo "${@: $start:$length}"
}
alias array.slice="array_slice"

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

Maven error: Not authorized, ReasonPhrase:Unauthorized

The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:

<servers>
    <server>
      <id>SomeRepo</id>
      <username>SomeUN</username>
      <password>SomePW</password>
    </server>
</servers>

ps: I guess your target is mvn clean install instead of maven install clean

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

COM is definitely not a good way to go. More specifically, it's a no go if you're dealing with web environment...

I've used with success the following open source projects:

  • ExcelPackage for OOXML formats (Office 2007)

  • NPOI for .XLS format (Office 2003)

Take a look at these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

Including a css file in a blade template?

Work with this code :

{!! include ('css/app.css') !!}

How to force file download with PHP

try this:

header('Content-type: audio/mp3'); 
header('Content-disposition: attachment; 
filename=“'.$trackname'”');                             
readfile('folder name /'.$trackname);          
exit();

Can Selenium interact with an existing browser session?

I got a solution in python, I modified the webdriver class bassed on PersistenBrowser class that I found.

https://github.com/axelPalmerin/personal/commit/fabddb38a39f378aa113b0cb8d33391d5f91dca5

replace the webdriver module /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py

Ej. to use:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

runDriver = sys.argv[1]
sessionId = sys.argv[2]

def setBrowser():
    if eval(runDriver):
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                     desired_capabilities=DesiredCapabilities.CHROME,
                     )
    else:
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                             desired_capabilities=DesiredCapabilities.CHROME,
                             session_id=sessionId)

    url = webdriver.command_executor._url
    session_id = webdriver.session_id
    print url
    print session_id
    return webdriver

Apply style ONLY on IE

As well as a conditional comment could also use CSS Browser Selector http://rafael.adm.br/css_browser_selector/ as this will allow you to target specific browsers. You can then set your CSS as

.ie .actual-form table {
    width: 100%
    }

This will also allow you to target specific browsers within your main stylesheet without the need for conditional comments.

How to limit the number of selected checkboxes?

I'd say like letiagoalves said, but you might have more than one checkbox question in your form, so I'd recommend to do like this:

  var limit = 3;
    $('input.single-checkbox').on('change', function(evt) {
        if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
            this.checked = false;
        }
    });

How to remove all non-alpha numeric characters from a string in MySQL?

Probably a silly suggestion compared to others:

if(!preg_match("/^[a-zA-Z0-9]$/",$string)){
    $sortedString=preg_replace("/^[a-zA-Z0-9]+$/","",$string);
}

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

Detecting when the 'back' button is pressed on a navbar

I have solved this problem by adding a UIControl to the navigationBar on the left side .

UIControl *leftBarItemControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
[leftBarItemControl addTarget:self action:@selector(onLeftItemClick:) forControlEvents:UIControlEventTouchUpInside];
self.leftItemControl = leftBarItemControl;
[self.navigationController.navigationBar addSubview:leftBarItemControl];
[self.navigationController.navigationBar bringSubviewToFront:leftBarItemControl];

And you need to remember to remove it when view will disappear:

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.leftItemControl) {
        [self.leftItemControl removeFromSuperview];
    }    
}

That's all!

NVIDIA NVML Driver/library version mismatch

Had the issue too. (I'm running ubuntu 18.04)

What I did:

dpkg -l | grep -i nvidia

Then sudo apt-get remove --purge nvidia-381 (and every duplicate version, in my case I had 381, 384 and 387)

Then sudo ubuntu-drivers devices to list what's available

And I choose sudo apt install nvidia-driver-430

After that, nvidia-smi gave the correct output (no need to reboot). But I suppose you can reboot when in doubt.

I also followed this installation to reinstall cuda+cudnn.

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

How to remove duplicate white spaces in string using Java?

hi the fastest (but not prettiest way) i found is

while (cleantext.indexOf("  ") != -1)
  cleantext = StringUtils.replace(cleantext, "  ", " ");

this is running pretty fast on android in opposite to an regex

package javax.servlet.http does not exist

The solution that work for is were add the next dependency to my pom.xml file.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

IDENTITY_INSERT is set to OFF - How to turn it ON?

Should you instead be setting the identity insert to on within the stored procedure? It looks like you're setting it to on only when changing the stored procedure, not when actually calling it. Try:

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 

SET IDENTITY_INSERT tbl_content ON

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

Amazon S3 direct file upload from client browser - private key disclosure

Adding more info to the accepted answer, you can refer to my blog to see a running version of the code, using AWS Signature version 4.

Will summarize here:

As soon as the user selects a file to be uploaded, do the followings: 1. Make a call to the web server to initiate a service to generate required params

  1. In this service, make a call to AWS IAM service to get temporary cred

  2. Once you have the cred, create a bucket policy (base 64 encoded string). Then sign the bucket policy with the temporary secret access key to generate final signature

  3. send the necessary parameters back to the UI

  4. Once this is received, create a html form object, set the required params and POST it.

For detailed info, please refer https://wordpress1763.wordpress.com/2016/10/03/browser-based-upload-aws-signature-version-4/

GridLayout (not GridView) how to stretch all children evenly

Starting in API 21 without v7 support library with ScrollView:

enter image description here

XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="2"
            >

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile1" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimaryDark"
            android:text="Tile2" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimary"
            android:text="Tile3" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile4" />

    </GridLayout>
</ScrollView>

Is it possible to animate scrollTop with jQuery?

If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:

$('body').animate({ scrollTop: $(document).height() });

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Just add -d32 to VM arguments in the "Edit launch configuration properties".

Command to open file with git

I just downloaded Git 2.7.0 and added an alias to the .bashrc for editing files with VS Code:

alias code='/c/Program\ Files\ \(x86\)/Microsoft\ VS\ Code/bin/code.cmd'

Should also work with other Editors...

Rewrite URL after redirecting 404 error htaccess

Try this in your .htaccess:

.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]

The ErrorDocument redirects all 404s to a specific URL, all 500s to another url (replace with your domain).

The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.

Local Redirect:

Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):

ErrorDocument 404 /pages/errors/404_redirect.php

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>

Redirect based on error number

Looks like you'll need to specify an ErrorDocument line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.

error_redirect.php

<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

What does the regex \S mean in JavaScript?

I believe it means 'anything but a whitespace character'.

Put buttons at bottom of screen with LinearLayout?

Just add layout_weight="1" to in your linearLayout which having Buttons.

Edit :- let me make it simple

follow something like below, tags name may not be correct, it is just an Idea

<LL>// Top Parrent LinearLayout
   <LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
   <LL2 height="wrap_content" weight="1"  orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen

<LL/> TOP PARENT CLOSED

Java - Change int to ascii

In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:

private static final char[] DIGITS =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

private static char getDigit(int digitValue) {
   assertInRange(digitValue, 0, 9);
   return DIGITS[digitValue];
}

Or, equivalently:

private static int ASCII_ZERO = 0x30;

private static char getDigit(int digitValue) {
  assertInRange(digitValue, 0, 9);
  return ((char) (digitValue + ASCII_ZERO));
}

How to format code in Xcode?

  1. Select the block of code that you want indented.

  2. Right-click (or, on Mac, Ctrl-click).

  3. Structure → Re-indent

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

IndentationError: unindent does not match any outer indentation level

for Atom Users, Packages ->whitspace -> remove trailing whitespaces this worked for me

Adding script tag to React/JSX

for multiple scripts, use this

var loadScript = function(src) {
  var tag = document.createElement('script');
  tag.async = false;
  tag.src = src;
  document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')

getting error while updating Composer

The good solution for this error please run this command

composer install --ignore-platform-reqs

CALL command vs. START with /WAIT option

This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.

In the end, piping the command through more did the trick.

setup.exe {arguments} | more

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

Android: No Activity found to handle Intent error? How it will resolve

Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:

Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
                    startActivity(i);

In this statement replace ActivityName by Name of Class of Activity, this code resides in.

Bad Request, Your browser sent a request that this server could not understand

In my case is a cookie-related issue, I had many cookies with value extremely big, and that was causing the problem.

You can replicate this issue here on stackoverflow.com, just open the console and type this:

[ ...Array(5) ].forEach((i, idx) => {
    document.cookie = `stackoverflow_cookie${idx}=${'a'.repeat(4000)}`;
});

What is that?

I am creating 5 cookies with a string of length or value of 4000 bytes; then reload the page and you will see the same issue.

I tried it on google.com and you'll get the error but they automatically clear the cookies for you, which is a nice fallback to start fresh.

Extension methods must be defined in a non-generic static class

Add keyword static to class declaration:

// this is a non-generic static class
public static class LinqHelper
{
}

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

Typescript export vs. default export

Named export

In TS you can export with the export keyword. It then can be imported via import {name} from "./mydir";. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:

// foo.js file
export class foo{}
export class bar{}

// main.js file in same dir
import {foo, bar} from "./foo";

The following alternative syntax is also valid:

// foo.js file
function foo() {};
function bar() {};
export {foo, bar};

// main.js file in same dir
import {foo, bar} from './foo'

Default export

We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.

// foo.js file
export default class foo{}

// main.js file in same directory
import abc from "./foo";

It's just JavaScript

Modules and their associated keyword like import, export, and export default are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.

PHP: Calling another class' method

You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA

class ClassA {
    public function getName() {
      echo $this->name;
    }
}

class ClassB extends ClassA {
    public function getName() {
      parent::getName();
    }
}

Without inheritance or an instance method, you'd need ClassA to have a static method

class ClassA {
  public static function getName() {
    echo "Rawkode";
  }
}

--- other file ---

echo ClassA::getName();

If you're just looking to call the method from an instance of the class:

class ClassA {
  public function getName() {
    echo "Rawkode";
  }
}

--- other file ---

$a = new ClassA();
echo $a->getName();

Regardless of the solution you choose, require 'ClassA.php is needed.

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How do I find out what version of WordPress is running?

Every WP install has a readme.html file.

So just type www.yourdomain.com/readme.html

Why does ANT tell me that JAVA_HOME is wrong when it is not?

I faced this problem when building my project with Jenkins. First, it could not find ant.bat, which was fixed by adding the path to ant.bat to the system environment variable path. Then ant could not find the jdk directory. This was fixed by right-clicking on my computer > properties > advanced > environment variables and creating a new environment variable called JAVA_HOME and assigning it a value of C:\Program Files\Java\jdk1.7.0_21. Don't create this environment variable in User Variables. Create it under System Variables only.
In both cases, I had to restart the system.

Removing an activity from the history stack

In the manifest you can add:

android:noHistory="true"

<activity
android:name=".ActivityName"
android:noHistory="true" />

You can also call

finish()

immediately after calling startActivity(..)

How to pass arguments to addEventListener listener function?

You could pass somevar by value(not by reference) via a javascript feature known as closure:

var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',function(someVar){
   return function(){func(someVar)}
}(someVar));
someVar='changed'

Or you could write a common wrap function such as wrapEventCallback:

function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'

Here wrapEventCallback(func,var1,var2) is like:

func.bind(null, var1,var2)

Convert a String to a byte array and then back to the original String

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

How to paste text to end of every line? Sublime 2

Use column selection. Column selection is one of the unique features of Sublime2; it is used to give you multiple matched cursors (tutorial here). To get multiple cursors, do one of the following:

Mouse:

  • Hold down the shift (Windows/Linux) or option key (Mac) while selecting a region with the mouse.

  • Clicking middle mouse button (or scroll) will select as a column also.

Keyboard:

  • Select the desired region.
  • Type control+shift+L (Windows/Linux) or command+shift+L (Mac)

You now have multiple lines selected, so you could type a quotation mark at the beginning and end of each line. It would be better to take advantage of Sublime's capabilities, and just type ". When you do this, Sublime automatically quotes the selected text.

Type esc to exit multiple cursor mode.

Replace whitespace with a comma in a text file in Linux

without looking at your input file, only a guess

awk '{$1=$1}1' OFS=","

redirect to another file and rename as needed

py2exe - generate single executable file

try c_x freeze it can create a good standalone

What is the standard Python docstring format?

The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

'JSON' is undefined error in JavaScript in Internet Explorer

Check for extra commas in your JSON response. If the last element of an array has a comma, this will break in IE

Get the Id of current table row with Jquery

$('#tblCart tr').click(function () {
        var tr_id = $(this).attr('id'); 
        alert(tr_id );
    });



<table class="table table-striped table-bordered table-hover" id="tblCart" cellspacing="0" align="center" >
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Item.ItemName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Price.PriceAmount)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Quantity)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Subtotal)
                    </th>
                    <th></th>
                </tr>

               @if (cart != null)
               {
                   foreach (var vm in cart)
                   {
                    <tr id="@vm.Id">
                        <td>
                            @Html.DisplayFor(modelItem => vm.Item.ItemName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Price.PriceAmount)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Quantity)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Subtotal)
                        </td>
                        <td >                            
                            <span style="width:80px; text-align:center;" class="glyphicon glyphicon-minus-sign" />                        
                        </td>
                    </tr>  
                   }
               }
            </table>

Cross-reference (named anchor) in markdown

For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:

# My Anchored Heading {#my-anchor}

Then link to this anchor like this

[link to my anchored heading](#my-anchor)

Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/

What is the difference between attribute and property?

In Python...

class X( object ):
    def __init__( self ):
        self.attribute
    def getAttr( self ):
        return self.attribute
    def setAttr( self, value ):
        self.attribute= value
    property_name= property( getAttr, setAttr )

A property is a single attribute-like name that wraps a collection of setter, getter (and deleter) functions.

An attribute is usually a single object within another object.

Having said that, however, Python gives you methods like __getattr__ which allow you extend the definition of "attribute".

Bottom Line - they're almost synonymous. Python makes a technical distinction in how they're implemented.

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

Remove all items from a FormArray in Angular

To keep the code clean I have created the following extension method for anyone using Angular 7 and below. This can also be used to extend any other functionality of Reactive Forms.

import { FormArray } from '@angular/forms';

declare module '@angular/forms/src/model' {
  interface FormArray {
    clearArray: () => FormArray;
  }
}

FormArray.prototype.clearArray = function () {
  const _self = this as FormArray;
  _self.controls = [];
  _self.setValue([]);
  _self.updateValueAndValidity();
  return _self;
}

Mocking member variables of a class using Mockito

Lots of others have already advised you to rethink your code to make it more testable - good advice and usually simpler than what I'm about to suggest.

If you can't change the code to make it more testable, PowerMock: https://code.google.com/p/powermock/

PowerMock extends Mockito (so you don't have to learn a new mock framework), providing additional functionality. This includes the ability to have a constructor return a mock. Powerful, but a little complicated - so use it judiciously.

You use a different Mock runner. And you need to prepare the class that is going to invoke the constructor. (Note that this is a common gotcha - prepare the class that calls the constructor, not the constructed class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class})

Then in your test set-up, you can use the whenNew method to have the constructor return a mock

whenNew(Second.class).withAnyArguments().thenReturn(mock(Second.class));

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Find .xcodeproj file and open it with a text editor

Find fields below and make them like this

CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";

PROVISIONING_PROFILE = "";

PROVISIONING_PROFILE_SPECIFIER = "";

SQL SERVER: Get total days between two dates

See DateDiff:

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)

How to format numbers?

This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):

function addSeperator(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

How do I save a String to a text file using Java?

I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}

Convert string to nullable type (int, double, etc...)

The generic answer provided by "Joel Coehoorn" is good.

But, this is another way without using those GetConverter... or try/catch blocks... (i'm not sure but this may have better performance in some cases):

public static class StrToNumberExtensions
{
    public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;

    public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}

Usage is as following:

var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null 
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1

var y = "19.50".ToDecimal(); //19.50

var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

Prevent linebreak after </div>

The div elements are block elements, so by default they take upp the full available width.

One way is to turn them into inline elements:

.label, .text { display: inline; }

This will have the same effect as using span elements instead of div elements.

Another way is to float the elements:

.label, .text { float: left; }

This will change how the width of the elements is decided, so that thwy will only be as wide as their content. It will also make the elements float beside each other, similar to how images flow beside each other.

You can also consider changing the elements. The div element is intended for document divisions, I usually use a label and a span element for a construct like this:

<label>My Label:</label>
<span>My text</span>

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

How should I set the default proxy to use default credentials?

This thread is old, but I just recently stumbled over the defaultProxy issue and maybe it helps others.

I used the config setting as Andrew suggested. When deploying it, my customer got an error saying, there weren't sufficient rights to set the configuration 'defaultProxy'.

Not knowing why I do not have the right to set this configuration and what to do about it, I just removed it and it still worked. So it seems that in VS2013 this issue is fixed.

And while we're at it:

    WebRequest.DefaultWebProxy.Credentials = new NetworkCredential("ProxyUsername", "ProxyPassword");

uses the default proxy with your credentials. If you want to force not using a proxy just set the DefaultWebProxy to null (though I don't know if one wants that).

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

How to remove \n from a list element?

It sounds like you want something like the Perl chomp() function.

That's trivial to do in Python:

def chomp(s):
    return s[:-1] if s.endswith('\n') else s

... assuming you're using Python 2.6 or later. Otherwise just use the slightly more verbose:

def chomp(s):
    if s.endwith('\n'):
        return s[:-1]
    else:
        return s

If you want to remove all new lines from the end of a string (in the odd case where one might have multiple trailing newlines for some reason):

def chomps(s):
    return s.rstrip('\n')

Obviously you should never see such a string returned by any normal Python file object's readline() nor readlines() methods.

I've seen people blindly remove the last characters (using s[:-1] slicing) from the results of file readline() and similar functions. This is a bad idea because it can lead to an error on the last line of the file (in the case where a file ends with anything other than a newline).

At first you might be lulled into a false sense of security when blindly stripping final characters off lines you've read. If you use a normal text editor to create your test suite files you'll have a newline silently added to the end of the last line by most of them. To create a valid test file use code something like:

f = open('sometest.txt', 'w')
f.write('some text')
f.close()

... and then if you re-open that file and use the readline() or readlines() file methods on it you'll find that the text is read without the trailing newline.

This failure to account for text files ending in non-newline characters has plagued many UNIX utilities and scripting languages for many years. It's a stupid corner base bug that creeps into code just often enough to be a pest but not often enough for people to learn from it. We could argue that "text" files without the ultimate newline are "corrupt" or non-standard; and that may be valid for some programming specifications.

However, it's all too easy to ignore corner cases in our coding and have that ignorance bite people who are depending on your code later. As my wife says: when it comes to programming ... practice safe hex!

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

Install specific version using laravel installer

use laravel new blog --5.1
make sure you must have laravel installer 1.3.4 version.

Best way to combine two or more byte arrays in C#

    public static bool MyConcat<T>(ref T[] base_arr, ref T[] add_arr)
    {
        try
        {
            int base_size = base_arr.Length;
            int size_T = System.Runtime.InteropServices.Marshal.SizeOf(base_arr[0]);
            Array.Resize(ref base_arr, base_size + add_arr.Length);
            Buffer.BlockCopy(add_arr, 0, base_arr, base_size * size_T, add_arr.Length * size_T);
        }
        catch (IndexOutOfRangeException ioor)
        {
            MessageBox.Show(ioor.Message);
            return false;
        }
        return true;
    }

Check if an object belongs to a class in Java

I agree with the use of instanceof already mentioned.

An additional benefit of using instanceof is that when used with a null reference instanceof of will return false, while a.getClass() would throw a NullPointerException.

What exactly is \r in C language?

'\r' is the carriage return character. The main times it would be useful are:

  1. When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.

  2. When writing to an interactive terminal on stdout or stderr, '\r' can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.

The example code in your post is definitely a wrong way to use '\r'. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n' (newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).

Getting the current Fragment instance in the viewpager

In my previous implementation I stored a list of child Fragments to be able to access them later, but this turned out to be a wrong implementation causing huge memory leaks.

I end up using instantiateItem(...) method to get current Fragment:

val currentFragment = adapter?.instantiateItem(viewPager, viewPager.currentItem)

Or to get any other Fragment on position:

val position = 0
val myFirstFragment: MyFragment? = (adapter?.instantiateItem(viewPager, position) as? MyFragment)

From documentation:

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from finishUpdate(ViewGroup).

How do I clone a job in Jenkins?

Create a new Item and go to the last you'll find option to copy from existing, just write your current job name and you will have clone of that project to work with.

Get variable from PHP to JavaScript

I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.

In your HTML pages, you can request data from the PHP scripts like this:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).

Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

Will using 'var' affect performance?

I don't think you properly understood what you read. If it gets compiled to the correct type, then there is no difference. When I do this:

var i = 42;

The compiler knows it's an int, and generate code as if I had written

int i = 42;

As the post you linked to says, it gets compiled to the same type. It's not a runtime check or anything else requiring extra code. The compiler just figures out what the type must be, and uses that.

Find maximum value of a column and return the corresponding row values using Pandas

You can use:

print(df[df['Value']==df['Value'].max()])

Count the number of occurrences of a character in a string in Javascript

Here is my solution. Lots of solution already posted before me. But I love to share my view here.

const mainStr = 'str1,str2,str3,str4';

const commaAndStringCounter = (str) => {
  const commas = [...str].filter(letter => letter === ',').length;
  const numOfStr = str.split(',').length;

  return `Commas: ${commas}, String: ${numOfStr}`;
}

// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4

Here you find my REPL

font awesome icon in select option

Full Sample and newer version:https://codepen.io/Nagibaba/pen/bagEgx enter image description here

_x000D_
_x000D_
select {_x000D_
  font-family: 'FontAwesome', 'sans-serif';_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<div>_x000D_
  <select>_x000D_
    <option value="fa-align-left">&#xf036; fa-align-left</option>_x000D_
    <option value="fa-align-right">&#xf038; fa-align-right</option>_x000D_
    <option value="fa-amazon">&#xf270; fa-amazon</option>_x000D_
    <option value="fa-ambulance">&#xf0f9; fa-ambulance</option>_x000D_
    <option value="fa-anchor">&#xf13d; fa-anchor</option>_x000D_
    <option value="fa-android">&#xf17b; fa-android</option>_x000D_
    <option value="fa-angellist">&#xf209; fa-angellist</option>_x000D_
    <option value="fa-angle-double-down">&#xf103; fa-angle-double-down</option>_x000D_
    <option value="fa-angle-double-left">&#xf100; fa-angle-double-left</option>_x000D_
    <option value="fa-angle-double-right">&#xf101; fa-angle-double-right</option>_x000D_
    <option value="fa-angle-double-up">&#xf102; fa-angle-double-up</option>_x000D_
_x000D_
    <option value="fa-angle-left">&#xf104; fa-angle-left</option>_x000D_
    <option value="fa-angle-right">&#xf105; fa-angle-right</option>_x000D_
    <option value="fa-angle-up">&#xf106; fa-angle-up</option>_x000D_
    <option value="fa-apple">&#xf179; fa-apple</option>_x000D_
    <option value="fa-archive">&#xf187; fa-archive</option>_x000D_
    <option value="fa-area-chart">&#xf1fe; fa-area-chart</option>_x000D_
    <option value="fa-arrow-circle-down">&#xf0ab; fa-arrow-circle-down</option>_x000D_
    <option value="fa-arrow-circle-left">&#xf0a8; fa-arrow-circle-left</option>_x000D_
    <option value="fa-arrow-circle-o-down">&#xf01a; fa-arrow-circle-o-down</option>_x000D_
    <option value="fa-arrow-circle-o-left">&#xf190; fa-arrow-circle-o-left</option>_x000D_
    <option value="fa-arrow-circle-o-right">&#xf18e; fa-arrow-circle-o-right</option>_x000D_
    <option value="fa-arrow-circle-o-up">&#xf01b; fa-arrow-circle-o-up</option>_x000D_
    <option value="fa-arrow-circle-right">&#xf0a9; fa-arrow-circle-right</option>_x000D_
    <option value="fa-arrow-circle-up">&#xf0aa; fa-arrow-circle-up</option>_x000D_
    <option value="fa-arrow-down">&#xf063; fa-arrow-down</option>_x000D_
    <option value="fa-arrow-left">&#xf060; fa-arrow-left</option>_x000D_
    <option value="fa-arrow-right">&#xf061; fa-arrow-right</option>_x000D_
    <option value="fa-arrow-up">&#xf062; fa-arrow-up</option>_x000D_
    <option value="fa-arrows">&#xf047; fa-arrows</option>_x000D_
    <option value="fa-arrows-alt">&#xf0b2; fa-arrows-alt</option>_x000D_
    <option value="fa-arrows-h">&#xf07e; fa-arrows-h</option>_x000D_
    <option value="fa-arrows-v">&#xf07d; fa-arrows-v</option>_x000D_
    <option value="fa-asterisk">&#xf069; fa-asterisk</option>_x000D_
    <option value="fa-at">&#xf1fa; fa-at</option>_x000D_
    <option value="fa-automobile">&#xf1b9; fa-automobile</option>_x000D_
    <option value="fa-backward">&#xf04a; fa-backward</option>_x000D_
    <option value="fa-balance-scale">&#xf24e; fa-balance-scale</option>_x000D_
    <option value="fa-ban">&#xf05e; fa-ban</option>_x000D_
    <option value="fa-bank">&#xf19c; fa-bank</option>_x000D_
    <option value="fa-bar-chart">&#xf080; fa-bar-chart</option>_x000D_
    <option value="fa-bar-chart-o">&#xf080; fa-bar-chart-o</option>_x000D_
_x000D_
    <option value="fa-battery-full">&#xf240; fa-battery-full</option>_x000D_
    n value="fa-beer">&#xf0fc; fa-beer</option>_x000D_
    <option value="fa-behance">&#xf1b4; fa-behance</option>_x000D_
    <option value="fa-behance-square">&#xf1b5; fa-behance-square</option>_x000D_
    <option value="fa-bell">&#xf0f3; fa-bell</option>_x000D_
    <option value="fa-bell-o">&#xf0a2; fa-bell-o</option>_x000D_
    <option value="fa-bell-slash">&#xf1f6; fa-bell-slash</option>_x000D_
    <option value="fa-bell-slash-o">&#xf1f7; fa-bell-slash-o</option>_x000D_
    <option value="fa-bicycle">&#xf206; fa-bicycle</option>_x000D_
    <option value="fa-binoculars">&#xf1e5; fa-binoculars</option>_x000D_
    <option value="fa-birthday-cake">&#xf1fd; fa-birthday-cake</option>_x000D_
    <option value="fa-bitbucket">&#xf171; fa-bitbucket</option>_x000D_
    <option value="fa-bitbucket-square">&#xf172; fa-bitbucket-square</option>_x000D_
    <option value="fa-bitcoin">&#xf15a; fa-bitcoin</option>_x000D_
    <option value="fa-black-tie">&#xf27e; fa-black-tie</option>_x000D_
    <option value="fa-bold">&#xf032; fa-bold</option>_x000D_
    <option value="fa-bolt">&#xf0e7; fa-bolt</option>_x000D_
    <option value="fa-bomb">&#xf1e2; fa-bomb</option>_x000D_
    <option value="fa-book">&#xf02d; fa-book</option>_x000D_
    <option value="fa-bookmark">&#xf02e; fa-bookmark</option>_x000D_
    <option value="fa-bookmark-o">&#xf097; fa-bookmark-o</option>_x000D_
    <option value="fa-briefcase">&#xf0b1; fa-briefcase</option>_x000D_
    <option value="fa-btc">&#xf15a; fa-btc</option>_x000D_
    <option value="fa-bug">&#xf188; fa-bug</option>_x000D_
    <option value="fa-building">&#xf1ad; fa-building</option>_x000D_
    <option value="fa-building-o">&#xf0f7; fa-building-o</option>_x000D_
    <option value="fa-bullhorn">&#xf0a1; fa-bullhorn</option>_x000D_
    <option value="fa-bullseye">&#xf140; fa-bullseye</option>_x000D_
    <option value="fa-bus">&#xf207; fa-bus</option>_x000D_
    <option value="fa-cab">&#xf1ba; fa-cab</option>_x000D_
    <option value="fa-calendar">&#xf073; fa-calendar</option>_x000D_
    <option value="fa-camera">&#xf030; fa-camera</option>_x000D_
    <option value="fa-car">&#xf1b9; fa-car</option>_x000D_
    <option value="fa-caret-up">&#xf0d8; fa-caret-up</option>_x000D_
    <option value="fa-cart-plus">&#xf217; fa-cart-plus</option>_x000D_
    <option value="fa-cc">&#xf20a; fa-cc</option>_x000D_
    <option value="fa-cc-amex">&#xf1f3; fa-cc-amex</option>_x000D_
    <option value="fa-cc-jcb">&#xf24b; fa-cc-jcb</option>_x000D_
    <option value="fa-cc-paypal">&#xf1f4; fa-cc-paypal</option>_x000D_
    <option value="fa-cc-stripe">&#xf1f5; fa-cc-stripe</option>_x000D_
    <option value="fa-cc-visa">&#xf1f0; fa-cc-visa</option>_x000D_
    <option value="fa-chain">&#xf0c1; fa-chain</option>_x000D_
    <option value="fa-check">&#xf00c; fa-check</option>_x000D_
    <option value="fa-chevron-left">&#xf053; fa-chevron-left</option>_x000D_
    <option value="fa-chevron-right">&#xf054; fa-chevron-right</option>_x000D_
    <option value="fa-chevron-up">&#xf077; fa-chevron-up</option>_x000D_
    <option value="fa-child">&#xf1ae; fa-child</option>_x000D_
    <option value="fa-chrome">&#xf268; fa-chrome</option>_x000D_
    <option value="fa-circle">&#xf111; fa-circle</option>_x000D_
    <option value="fa-circle-o">&#xf10c; fa-circle-o</option>_x000D_
    <option value="fa-circle-o-notch">&#xf1ce; fa-circle-o-notch</option>_x000D_
    <option value="fa-circle-thin">&#xf1db; fa-circle-thin</option>_x000D_
    <option value="fa-clipboard">&#xf0ea; fa-clipboard</option>_x000D_
    <option value="fa-clock-o">&#xf017; fa-clock-o</option>_x000D_
    <option value="fa-clone">&#xf24d; fa-clone</option>_x000D_
    <option value="fa-close">&#xf00d; fa-close</option>_x000D_
    <option value="fa-cloud">&#xf0c2; fa-cloud</option>_x000D_
    <option value="fa-cloud-download">&#xf0ed; fa-cloud-download</option>_x000D_
    <option value="fa-cloud-upload">&#xf0ee; fa-cloud-upload</option>_x000D_
    <option value="fa-cny">&#xf157; fa-cny</option>_x000D_
    <option value="fa-code">&#xf121; fa-code</option>_x000D_
    <option value="fa-code-fork">&#xf126; fa-code-fork</option>_x000D_
    <option value="fa-codepen">&#xf1cb; fa-codepen</option>_x000D_
    <option value="fa-coffee">&#xf0f4; fa-coffee</option>_x000D_
    <option value="fa-cog">&#xf013; fa-cog</option>_x000D_
    <option value="fa-cogs">&#xf085; fa-cogs</option>_x000D_
    <option value="fa-columns">&#xf0db; fa-columns</option>_x000D_
    <option value="fa-comment">&#xf075; fa-comment</option>_x000D_
    <option value="fa-comment-o">&#xf0e5; fa-comment-o</option>_x000D_
    <option value="fa-commenting">&#xf27a; fa-commenting</option>_x000D_
    <option value="fa-commenting-o">&#xf27b; fa-commenting-o</option>_x000D_
    <option value="fa-comments">&#xf086; fa-comments</option>_x000D_
    <option value="fa-comments-o">&#xf0e6; fa-comments-o</option>_x000D_
    <option value="fa-compass">&#xf14e; fa-compass</option>_x000D_
    <option value="fa-compress">&#xf066; fa-compress</option>_x000D_
    <option value="fa-connectdevelop">&#xf20e; fa-connectdevelop</option>_x000D_
    <option value="fa-contao">&#xf26d; fa-contao</option>_x000D_
    <option value="fa-copy">&#xf0c5; fa-copy</option>_x000D_
    <option value="fa-copyright">&#xf1f9; fa-copyright</option>_x000D_
    <option value="fa-creative-commons">&#xf25e; fa-creative-commons</option>_x000D_
    <option value="fa-credit-card">&#xf09d; fa-credit-card</option>_x000D_
    <option value="fa-crop">&#xf125; fa-crop</option>_x000D_
    <option value="fa-crosshairs">&#xf05b; fa-crosshairs</option>_x000D_
    <option value="fa-css3">&#xf13c; fa-css3</option>_x000D_
    <option value="fa-cube">&#xf1b2; fa-cube</option>_x000D_
    <option value="fa-cubes">&#xf1b3; fa-cubes</option>_x000D_
    <option value="fa-cut">&#xf0c4; fa-cut</option>_x000D_
    <option value="fa-cutlery">&#xf0f5; fa-cutlery</option>_x000D_
    <option value="fa-dashboard">&#xf0e4; fa-dashboard</option>_x000D_
    <option value="fa-dashcube">&#xf210; fa-dashcube</option>_x000D_
    <option value="fa-database">&#xf1c0; fa-database</option>_x000D_
    <option value="fa-dedent">&#xf03b; fa-dedent</option>_x000D_
    <option value="fa-delicious">&#xf1a5; fa-delicious</option>_x000D_
    <option value="fa-desktop">&#xf108; fa-desktop</option>_x000D_
    <option value="fa-deviantart">&#xf1bd; fa-deviantart</option>_x000D_
    <option value="fa-diamond">&#xf219; fa-diamond</option>_x000D_
    <option value="fa-digg">&#xf1a6; fa-digg</option>_x000D_
    <option value="fa-dollar">&#xf155; fa-dollar</option>_x000D_
    <option value="fa-download">&#xf019; fa-download</option>_x000D_
    <option value="fa-dribbble">&#xf17d; fa-dribbble</option>_x000D_
    <option value="fa-dropbox">&#xf16b; fa-dropbox</option>_x000D_
    <option value="fa-drupal">&#xf1a9; fa-drupal</option>_x000D_
    <option value="fa-edit">&#xf044; fa-edit</option>_x000D_
    <option value="fa-eject">&#xf052; fa-eject</option>_x000D_
    <option value="fa-ellipsis-h">&#xf141; fa-ellipsis-h</option>_x000D_
    <option value="fa-ellipsis-v">&#xf142; fa-ellipsis-v</option>_x000D_
    <option value="fa-empire">&#xf1d1; fa-empire</option>_x000D_
    <option value="fa-envelope">&#xf0e0; fa-envelope</option>_x000D_
    <option value="fa-envelope-o">&#xf003; fa-envelope-o</option>_x000D_
    <option value="fa-eur">&#xf153; fa-eur</option>_x000D_
    <option value="fa-euro">&#xf153; fa-euro</option>_x000D_
    <option value="fa-exchange">&#xf0ec; fa-exchange</option>_x000D_
    <option value="fa-exclamation">&#xf12a; fa-exclamation</option>_x000D_
    <option value="fa-exclamation-circle">&#xf06a; fa-exclamation-circle</option>_x000D_
    <option value="fa-exclamation-triangle">&#xf071; fa-exclamation-triangle</option>_x000D_
    <option value="fa-expand">&#xf065; fa-expand</option>_x000D_
    <option value="fa-expeditedssl">&#xf23e; fa-expeditedssl</option>_x000D_
    <option value="fa-external-link">&#xf08e; fa-external-link</option>_x000D_
    <option value="fa-external-link-square">&#xf14c; fa-external-link-square</option>_x000D_
    <option value="fa-eye">&#xf06e; fa-eye</option>_x000D_
    <option value="fa-eye-slash">&#xf070; fa-eye-slash</option>_x000D_
    <option value="fa-eyedropper">&#xf1fb; fa-eyedropper</option>_x000D_
    <option value="fa-facebook">&#xf09a; fa-facebook</option>_x000D_
    <option value="fa-facebook-f">&#xf09a; fa-facebook-f</option>_x000D_
    <option value="fa-facebook-official">&#xf230; fa-facebook-official</option>_x000D_
    <option value="fa-facebook-square">&#xf082; fa-facebook-square</option>_x000D_
    <option value="fa-fast-backward">&#xf049; fa-fast-backward</option>_x000D_
    <option value="fa-fast-forward">&#xf050; fa-fast-forward</option>_x000D_
    <option value="fa-fax">&#xf1ac; fa-fax</option>_x000D_
    <option value="fa-feed">&#xf09e; fa-feed</option>_x000D_
    <option value="fa-female">&#xf182; fa-female</option>_x000D_
    <option value="fa-fighter-jet">&#xf0fb; fa-fighter-jet</option>_x000D_
    <option value="fa-file">&#xf15b; fa-file</option>_x000D_
    <option value="fa-file-archive-o">&#xf1c6; fa-file-archive-o</option>_x000D_
    <option value="fa-file-audio-o">&#xf1c7; fa-file-audio-o</option>_x000D_
    <option value="fa-file-code-o">&#xf1c9; fa-file-code-o</option>_x000D_
    <option value="fa-file-excel-o">&#xf1c3; fa-file-excel-o</option>_x000D_
    <option value="fa-file-image-o">&#xf1c5; fa-file-image-o</option>_x000D_
    <option value="fa-file-movie-o">&#xf1c8; fa-file-movie-o</option>_x000D_
    <option value="fa-file-o">&#xf016; fa-file-o</option>_x000D_
    <option value="fa-file-pdf-o">&#xf1c1; fa-file-pdf-o</option>_x000D_
    <option value="fa-file-photo-o">&#xf1c5; fa-file-photo-o</option>_x000D_
    <option value="fa-file-picture-o">&#xf1c5; fa-file-picture-o</option>_x000D_
    <option value="fa-file-powerpoint-o">&#xf1c4; fa-file-powerpoint-o</option>_x000D_
    <option value="fa-file-sound-o">&#xf1c7; fa-file-sound-o</option>_x000D_
    <option value="fa-file-text">&#xf15c; fa-file-text</option>_x000D_
    <option value="fa-file-text-o">&#xf0f6; fa-file-text-o</option>_x000D_
    <option value="fa-file-video-o">&#xf1c8; fa-file-video-o</option>_x000D_
    <option value="fa-file-word-o">&#xf1c2; fa-file-word-o</option>_x000D_
    <option value="fa-file-zip-o">&#xf1c6; fa-file-zip-o</option>_x000D_
    <option value="fa-files-o">&#xf0c5; fa-files-o</option>_x000D_
    <option value="fa-film">&#xf008; fa-film</option>_x000D_
    <option value="fa-filter">&#xf0b0; fa-filter</option>_x000D_
    <option value="fa-fire">&#xf06d; fa-fire</option>_x000D_
    <option value="fa-fire-extinguisher">&#xf134; fa-fire-extinguisher</option>_x000D_
    <option value="fa-firefox">&#xf269; fa-firefox</option>_x000D_
    <option value="fa-flag">&#xf024; fa-flag</option>_x000D_
    <option value="fa-flag-checkered">&#xf11e; fa-flag-checkered</option>_x000D_
    <option value="fa-flag-o">&#xf11d; fa-flag-o</option>_x000D_
    <option value="fa-flash">&#xf0e7; fa-flash</option>_x000D_
    <option value="fa-flask">&#xf0c3; fa-flask</option>_x000D_
    <option value="fa-flickr">&#xf16e; fa-flickr</option>_x000D_
    <option value="fa-floppy-o">&#xf0c7; fa-floppy-o</option>_x000D_
    <option value="fa-folder">&#xf07b; fa-folder</option>_x000D_
    <option value="fa-folder-o">&#xf114; fa-folder-o</option>_x000D_
    <option value="fa-folder-open">&#xf07c; fa-folder-open</option>_x000D_
    <option value="fa-folder-open-o">&#xf115; fa-folder-open-o</option>_x000D_
    <option value="fa-font">&#xf031; fa-font</option>_x000D_
    <option value="fa-fonticons">&#xf280; fa-fonticons</option>_x000D_
    <option value="fa-forumbee">&#xf211; fa-forumbee</option>_x000D_
    <option value="fa-forward">&#xf04e; fa-forward</option>_x000D_
    <option value="fa-foursquare">&#xf180; fa-foursquare</option>_x000D_
    <option value="fa-frown-o">&#xf119; fa-frown-o</option>_x000D_
    <option value="fa-futbol-o">&#xf1e3; fa-futbol-o</option>_x000D_
    <option value="fa-gamepad">&#xf11b; fa-gamepad</option>_x000D_
    <option value="fa-gavel">&#xf0e3; fa-gavel</option>_x000D_
    <option value="fa-gbp">&#xf154; fa-gbp</option>_x000D_
    <option value="fa-ge">&#xf1d1; fa-ge</option>_x000D_
    <option value="fa-gear">&#xf013; fa-gear</option>_x000D_
    <option value="fa-gears">&#xf085; fa-gears</option>_x000D_
    <option value="fa-genderless">&#xf22d; fa-genderless</option>_x000D_
    <option value="fa-get-pocket">&#xf265; fa-get-pocket</option>_x000D_
    <option value="fa-gg">&#xf260; fa-gg</option>_x000D_
    <option value="fa-gg-circle">&#xf261; fa-gg-circle</option>_x000D_
    <option value="fa-gift">&#xf06b; fa-gift</option>_x000D_
    <option value="fa-git">&#xf1d3; fa-git</option>_x000D_
    <option value="fa-git-square">&#xf1d2; fa-git-square</option>_x000D_
    <option value="fa-github">&#xf09b; fa-github</option>_x000D_
    <option value="fa-github-alt">&#xf113; fa-github-alt</option>_x000D_
    <option value="fa-github-square">&#xf092; fa-github-square</option>_x000D_
    <option value="fa-gittip">&#xf184; fa-gittip</option>_x000D_
    <option value="fa-glass">&#xf000; fa-glass</option>_x000D_
    <option value="fa-globe">&#xf0ac; fa-globe</option>_x000D_
    <option value="fa-google">&#xf1a0; fa-google</option>_x000D_
    <option value="fa-google-plus">&#xf0d5; fa-google-plus</option>_x000D_
    <option value="fa-google-plus-square">&#xf0d4; fa-google-plus-square</option>_x000D_
    <option value="fa-google-wallet">&#xf1ee; fa-google-wallet</option>_x000D_
    <option value="fa-graduation-cap">&#xf19d; fa-graduation-cap</option>_x000D_
    <option value="fa-gratipay">&#xf184; fa-gratipay</option>_x000D_
    <option value="fa-group">&#xf0c0; fa-group</option>_x000D_
    <option value="fa-h-square">&#xf0fd; fa-h-square</option>_x000D_
    <option value="fa-hacker-news">&#xf1d4; fa-hacker-news</option>_x000D_
    <option value="fa-hand-grab-o">&#xf255; fa-hand-grab-o</option>_x000D_
    <option value="fa-hand-lizard-o">&#xf258; fa-hand-lizard-o</option>_x000D_
    <option value="fa-hand-o-down">&#xf0a7; fa-hand-o-down</option>_x000D_
    <option value="fa-hand-o-left">&#xf0a5; fa-hand-o-left</option>_x000D_
    <option value="fa-hand-o-right">&#xf0a4; fa-hand-o-right</option>_x000D_
    <option value="fa-hand-o-up">&#xf0a6; fa-hand-o-up</option>_x000D_
    <option value="fa-hand-paper-o">&#xf256; fa-hand-paper-o</option>_x000D_
    <option value="fa-hand-peace-o">&#xf25b; fa-hand-peace-o</option>_x000D_
    <option value="fa-hand-pointer-o">&#xf25a; fa-hand-pointer-o</option>_x000D_
    <option value="fa-hand-rock-o">&#xf255; fa-hand-rock-o</option>_x000D_
    <option value="fa-hand-scissors-o">&#xf257; fa-hand-scissors-o</option>_x000D_
    <option value="fa-hand-spock-o">&#xf259; fa-hand-spock-o</option>_x000D_
    <option value="fa-hand-stop-o">&#xf256; fa-hand-stop-o</option>_x000D_
    <option value="fa-hdd-o">&#xf0a0; fa-hdd-o</option>_x000D_
    <option value="fa-header">&#xf1dc; fa-header</option>_x000D_
    <option value="fa-headphones">&#xf025; fa-headphones</option>_x000D_
    <option value="fa-heart">&#xf004; fa-heart</option>_x000D_
    <option value="fa-heart-o">&#xf08a; fa-heart-o</option>_x000D_
    <option value="fa-heartbeat">&#xf21e; fa-heartbeat</option>_x000D_
    <option value="fa-history">&#xf1da; fa-history</option>_x000D_
    <option value="fa-home">&#xf015; fa-home</option>_x000D_
    <option value="fa-hospital-o">&#xf0f8; fa-hospital-o</option>_x000D_
    <option value="fa-hotel">&#xf236; fa-hotel</option>_x000D_
    <option value="fa-hourglass">&#xf254; fa-hourglass</option>_x000D_
    <option value="fa-hourglass-1">&#xf251; fa-hourglass-1</option>_x000D_
    <option value="fa-hourglass-2">&#xf252; fa-hourglass-2</option>_x000D_
    <option value="fa-hourglass-3">&#xf253; fa-hourglass-3</option>_x000D_
    <option value="fa-hourglass-end">&#xf253; fa-hourglass-end</option>_x000D_
    <option value="fa-hourglass-half">&#xf252; fa-hourglass-half</option>_x000D_
    <option value="fa-hourglass-o">&#xf250; fa-hourglass-o</option>_x000D_
    <option value="fa-hourglass-start">&#xf251; fa-hourglass-start</option>_x000D_
    <option value="fa-houzz">&#xf27c; fa-houzz</option>_x000D_
    <option value="fa-html5">&#xf13b; fa-html5</option>_x000D_
    <option value="fa-i-cursor">&#xf246; fa-i-cursor</option>_x000D_
    <option value="fa-ils">&#xf20b; fa-ils</option>_x000D_
    <option value="fa-image">&#xf03e; fa-image</option>_x000D_
    <option value="fa-inbox">&#xf01c; fa-inbox</option>_x000D_
    <option value="fa-indent">&#xf03c; fa-indent</option>_x000D_
    <option value="fa-industry">&#xf275; fa-industry</option>_x000D_
    <option value="fa-info">&#xf129; fa-info</option>_x000D_
    <option value="fa-info-circle">&#xf05a; fa-info-circle</option>_x000D_
    <option value="fa-inr">&#xf156; fa-inr</option>_x000D_
    <option value="fa-instagram">&#xf16d; fa-instagram</option>_x000D_
    <option value="fa-institution">&#xf19c; fa-institution</option>_x000D_
    <option value="fa-internet-explorer">&#xf26b; fa-internet-explorer</option>_x000D_
    <option value="fa-intersex">&#xf224; fa-intersex</option>_x000D_
    <option value="fa-ioxhost">&#xf208; fa-ioxhost</option>_x000D_
    <option value="fa-italic">&#xf033; fa-italic</option>_x000D_
    <option value="fa-joomla">&#xf1aa; fa-joomla</option>_x000D_
    <option value="fa-jpy">&#xf157; fa-jpy</option>_x000D_
    <option value="fa-jsfiddle">&#xf1cc; fa-jsfiddle</option>_x000D_
    <option value="fa-key">&#xf084; fa-key</option>_x000D_
    <option value="fa-keyboard-o">&#xf11c; fa-keyboard-o</option>_x000D_
    <option value="fa-krw">&#xf159; fa-krw</option>_x000D_
    <option value="fa-language">&#xf1ab; fa-language</option>_x000D_
    <option value="fa-laptop">&#xf109; fa-laptop</option>_x000D_
    <option value="fa-lastfm">&#xf202; fa-lastfm</option>_x000D_
    <option value="fa-lastfm-square">&#xf203; fa-lastfm-square</option>_x000D_
    <option value="fa-leaf">&#xf06c; fa-leaf</option>_x000D_
    <option value="fa-leanpub">&#xf212; fa-leanpub</option>_x000D_
    <option value="fa-legal">&#xf0e3; fa-legal</option>_x000D_
    <option value="fa-lemon-o">&#xf094; fa-lemon-o</option>_x000D_
    <option value="fa-level-down">&#xf149; fa-level-down</option>_x000D_
    <option value="fa-level-up">&#xf148; fa-level-up</option>_x000D_
    <option value="fa-life-bouy">&#xf1cd; fa-life-bouy</option>_x000D_
    <option value="fa-life-buoy">&#xf1cd; fa-life-buoy</option>_x000D_
    <option value="fa-life-ring">&#xf1cd; fa-life-ring</option>_x000D_
    <option value="fa-life-saver">&#xf1cd; fa-life-saver</option>_x000D_
    <option value="fa-lightbulb-o">&#xf0eb; fa-lightbulb-o</option>_x000D_
    <option value="fa-line-chart">&#xf201; fa-line-chart</option>_x000D_
    <option value="fa-link">&#xf0c1; fa-link</option>_x000D_
    <option value="fa-linkedin">&#xf0e1; fa-linkedin</option>_x000D_
    <option value="fa-linkedin-square">&#xf08c; fa-linkedin-square</option>_x000D_
    <option value="fa-linux">&#xf17c; fa-linux</option>_x000D_
    <option value="fa-list">&#xf03a; fa-list</option>_x000D_
    <option value="fa-list-alt">&#xf022; fa-list-alt</option>_x000D_
    <option value="fa-list-ol">&#xf0cb; fa-list-ol</option>_x000D_
    <option value="fa-list-ul">&#xf0ca; fa-list-ul</option>_x000D_
    <option value="fa-location-arrow">&#xf124; fa-location-arrow</option>_x000D_
    <option value="fa-lock">&#xf023; fa-lock</option>_x000D_
    <option value="fa-long-arrow-down">&#xf175; fa-long-arrow-down</option>_x000D_
    <option value="fa-long-arrow-left">&#xf177; fa-long-arrow-left</option>_x000D_
    <option value="fa-long-arrow-right">&#xf178; fa-long-arrow-right</option>_x000D_
    <option value="fa-long-arrow-up">&#xf176; fa-long-arrow-up</option>_x000D_
    <option value="fa-magic">&#xf0d0; fa-magic</option>_x000D_
    <option value="fa-magnet">&#xf076; fa-magnet</option>_x000D_
_x000D_
    <option value="fa-mars-stroke-v">&#xf22a; fa-mars-stroke-v</option>_x000D_
    <option value="fa-maxcdn">&#xf136; fa-maxcdn</option>_x000D_
    <option value="fa-meanpath">&#xf20c; fa-meanpath</option>_x000D_
    <option value="fa-medium">&#xf23a; fa-medium</option>_x000D_
    <option value="fa-medkit">&#xf0fa; fa-medkit</option>_x000D_
    <option value="fa-meh-o">&#xf11a; fa-meh-o</option>_x000D_
    <option value="fa-mercury">&#xf223; fa-mercury</option>_x000D_
    <option value="fa-microphone">&#xf130; fa-microphone</option>_x000D_
    <option value="fa-mobile">&#xf10b; fa-mobile</option>_x000D_
    <option value="fa-motorcycle">&#xf21c; fa-motorcycle</option>_x000D_
    <option value="fa-mouse-pointer">&#xf245; fa-mouse-pointer</option>_x000D_
    <option value="fa-music">&#xf001; fa-music</option>_x000D_
    <option value="fa-navicon">&#xf0c9; fa-navicon</option>_x000D_
    <option value="fa-neuter">&#xf22c; fa-neuter</option>_x000D_
    <option value="fa-newspaper-o">&#xf1ea; fa-newspaper-o</option>_x000D_
    <option value="fa-opencart">&#xf23d; fa-opencart</option>_x000D_
    <option value="fa-openid">&#xf19b; fa-openid</option>_x000D_
    <option value="fa-opera">&#xf26a; fa-opera</option>_x000D_
    <option value="fa-outdent">&#xf03b; fa-outdent</option>_x000D_
    <option value="fa-pagelines">&#xf18c; fa-pagelines</option>_x000D_
    <option value="fa-paper-plane-o">&#xf1d9; fa-paper-plane-o</option>_x000D_
    <option value="fa-paperclip">&#xf0c6; fa-paperclip</option>_x000D_
    <option value="fa-paragraph">&#xf1dd; fa-paragraph</option>_x000D_
    <option value="fa-paste">&#xf0ea; fa-paste</option>_x000D_
    <option value="fa-pause">&#xf04c; fa-pause</option>_x000D_
    <option value="fa-paw">&#xf1b0; fa-paw</option>_x000D_
    <option value="fa-paypal">&#xf1ed; fa-paypal</option>_x000D_
    <option value="fa-pencil">&#xf040; fa-pencil</option>_x000D_
    <option value="fa-pencil-square-o">&#xf044; fa-pencil-square-o</option>_x000D_
    <option value="fa-phone">&#xf095; fa-phone</option>_x000D_
    <option value="fa-photo">&#xf03e; fa-photo</option>_x000D_
    <option value="fa-picture-o">&#xf03e; fa-picture-o</option>_x000D_
    <option value="fa-pie-chart">&#xf200; fa-pie-chart</option>_x000D_
    <option value="fa-pied-piper">&#xf1a7; fa-pied-piper</option>_x000D_
    <option value="fa-pied-piper-alt">&#xf1a8; fa-pied-piper-alt</option>_x000D_
    <option value="fa-pinterest">&#xf0d2; fa-pinterest</option>_x000D_
    <option value="fa-pinterest-p">&#xf231; fa-pinterest-p</option>_x000D_
    <option value="fa-pinterest-square">&#xf0d3; fa-pinterest-square</option>_x000D_
    <option value="fa-plane">&#xf072; fa-plane</option>_x000D_
    <option value="fa-play">&#xf04b; fa-play</option>_x000D_
    <option value="fa-play-c
                  

ADB Android Device Unauthorized

It's likely that the device is no longer authorized on ADB for whatever reason.

1. Check if authorized:

<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d        unauthorized

2. Revoke USB Debugging on phone

If the device is shown as unauthorized, go to the developer options on the phone and click "Revoke USB debugging authorization" (tested with JellyBean & Samsung GalaxyIII).

3. Restart ADB Server:

Then restarted adb server

adb kill-server
adb start-server

4. Reconnect the device

The device will ask if you are agree to connect the computer id. You need to confirm it.

5. Now Check the device

It is now authorized!

adb devices
<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d        device

Get list of all tables in Oracle?

Simple query to select the tables for the current user:

  SELECT table_name FROM user_tables;

How to get rows count of internal table in abap?

  DATA : V_LINES TYPE I. "declare variable
  DESCRIBE TABLE <ITAB> LINES V_LINES. "get no of rows
  WRITE:/ V_LINES. "display no of rows

Refreance: http://www.sapnuts.com/courses/core-abap/internal-table-work-area.html

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

JAVA_HOME is not the name of the java executable. But of the directory, java was installed in. The executable should be $JAVA_HOME/bin/java.

The which command is not helpful for you there. It will not give you the java home, but most likely this is just a wrapper or symlink to java installed in a very different directory.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

Setting PHP tmp dir - PHP upload not working

The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

  • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

  • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

  • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

  • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

  • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

  • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

  • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

  • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

  • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

  • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

How to align center the text in html table row?

Selector > child:

_x000D_
_x000D_
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
  text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
  <tr class="text-center-row">_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
  <tr class="text-center-row">_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to pass arguments and redirect stdin from a file to program run in gdb?

If you want to have bare run command in gdb to execute your program with redirections and arguments, you can use set args:

% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run

I was unable to achieve the same behaviour with --args parameter, gdb fiercely escapes the redirections, i.e.

% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...

This one actually redirects the input of gdb itself, not what we really want here

% gdb --args echo 1 2 <file
zsh: no such file or directory: file

How do I detect if software keyboard is visible on Android Device or not?

There is no direct way - see http://groups.google.com/group/android-platform/browse_thread/thread/1728f26f2334c060/5e4910f0d9eb898a where Dianne Hackborn from the Android team has replied. However, you can detect it indirectly by checking if the window size changed in #onMeasure. See How to check visibility of software keyboard in Android?.

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How to restore the permissions of files and directories within git if they have been modified?

Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.

Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.

Converting Stream to String and back...what are we missing?

This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:

  • an arbitrary string to formatted bytes
  • formatted bytes to the original string

You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers

  • arbitrary bytes to a formatted string
  • a formatted string to the original bytes

look at Convert.ToBase64String and Convert. FromBase64String

How to render pdfs using C#

You could google for PDF viewer component, and come up with more than a few hits.

If you don't really need to embed them in your app, though - you can just require Acrobat Reader or FoxIt (or bundle it, if it meets their respective licensing terms) and shell out to it. It's not as cool, but it gets the job done for free.

Convert Array to Object

I ended up using object spread operator, since it is part of the ECMAScript 2015 (ES6) standard.

const array = ['a', 'b', 'c'];
console.log({...array});
// it outputs {0:'a', 1:'b', 2:'c'}

Made the following fiddle as an example.

Get value from text area

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

How should I throw a divide by zero exception in Java without actually dividing by zero?

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.

Responsive Bootstrap Jumbotron Background Image

You could try this:

Simply place the code in a style tag in the head of the html file

_x000D_
_x000D_
<style>_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }_x000D_
</style>
_x000D_
_x000D_
_x000D_

or put it in a separate css file as shown below

_x000D_
_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }
_x000D_
_x000D_
_x000D_

use center center to center the image horizontally and vertically. use cover to make the image fill out the jumbotron space and finally no-repeat so that the image is not repeated.

Wait some seconds without blocking UI execution

If possible, the preferred approach should be using an asynchronous way or a second thread.

If this isn't possible or wanted, using any implementation of DoEvents() is a bad idea, since it may cause problems Possible problems with DoEvents. This is mostly about DoEvents with Winforms but the possible pitfalls in WPF are the same.

Then putting a frame on the Dispatcher with the wanted sleep time can be used:

using System;
using System.Threading;
using System.Windows.Threading;

public static void NonBlockingSleep(int timeInMilliseconds)
{
    DispatcherFrame df = new DispatcherFrame();

    new Thread((ThreadStart)(() =>
    {
        Thread.Sleep(TimeSpan.FromMilliseconds(timeInMilliseconds));
        df.Continue = false;

    })).Start();

    Dispatcher.PushFrame(df);
}

Where does pip install its packages?

One can import the package then consult its help

import statsmodels
help(sm)

At the very bottom of the help there is a section FILE that indicates where this package was installed.

This solution was tested with at least matplotlib (3.1.2) and statsmodels (0.11.1) (python 3.8.2).

jQuery: get the file name selected from <input type="file" />

$('input[type=file]').change(function(e){
    $(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});

This code will not show C:\fakepath\ before file name in Google Chrome in case of using .val().

How to tell if JRE or JDK is installed

You can open up terminal and simply type

java -version // this will check your jre version
javac -version // this will check your java compiler version if you installed 

this should show you the version of java installed on the system (assuming that you have set the path of the java in system environment).

And if you haven't, add it via

export JAVA_HOME=/path/to/java/jdk1.x

and if you unsure if you have java at all on your system just use find in terminal

i.e. find / -name "java"

Format JavaScript date as yyyy-mm-dd

This worked for me to get the current date in the desired format (YYYYMMDD HH:MM:SS):

var d = new Date();

var date1 = d.getFullYear() + '' +
            ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
            '' +
            (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());

var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
            ':' +
            (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
            ':' +
            (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());

print(date1+' '+time1);

Get index of a key in json

What you have is a string representing a JSON serialized javascript object. You need to deserialize it back a javascript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
    var result = $.parseJSON(resultJSON);
    $.each(result, function(k, v) {
        //display the key and value pair
        alert(k + ' is ' + v);
    });

or simply:

arr.forEach(function (val, index, theArray) {
    //do stuff
});

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

String to Binary in C#

It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010

This will do that for you...

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}

Powershell remoting with ip-address as target

On Windows 10 it is important to make sure the WinRM Service is running to invoke the command

* Set-Item wsman:\localhost\Client\TrustedHosts -value '*' -Force *

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

Node.js global variables

You can use global like so:

global._ = require('underscore')

Get the string value from List<String> through loop for display

Try following if your looking for while loop implementation.

List<String> myString = new ArrayList<String>();

// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");

int i = 0;
while (i < myString.size()) {
    System.out.println(myString.get(i));
    i++;
}

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Im using QtCreator with gdb.

Adding

QMAKE_CXXFLAGS += -O0
QMAKE_CXXFLAGS -= -O1
QMAKE_CXXFLAGS -= -O2
QMAKE_CXXFLAGS -= -O3

Works well for me

javascript create empty array of a given size

1) To create new array which, you cannot iterate over, you can use array constructor:

Array(100) or new Array(100)


2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

  • Array.apply: Array.apply(null, Array(100))

b) From ES6 JavaScript version

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

Function pointer as parameter

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

How to set background color of HTML element using css properties in JavaScript

$('#ID / .Class').css('background-color', '#FF6600');

By using jquery we can target the element's class or Id to apply css background or any other stylings

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

How to select the last record of a table in SQL?

MS SQL Server has supported ANSI SQL FETCH FIRST for many years now:

SELECT * FROM TABLE
ORDER BY ID DESC 
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY

(Works with most modern databases.)

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

How to use find command to find all files with extensions from list?

find /path/to/  \( -iname '*.gif' -o -iname '*.jpg' \) -print0

will work. There might be a more elegant way.

Sorting a Dictionary in place with respect to keys

The correct answer is already stated (just use SortedDictionary).

However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...

Dictionary<string, int> dupcheck = new Dictionary<string, int>();

...some code that fills in "dupcheck", then...

if (dupcheck.Count > 0) {
  Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
  var keys_sorted = dupcheck.Keys.ToList();
    keys_sorted.Sort();
  foreach (var k in keys_sorted) {
    Console.WriteLine("{0} = {1}", k, dupcheck[k]);
  }
}

Don't forget using System.Linq; for this.

Save text file UTF-8 encoded with VBA

The traditional way to transform a string to a UTF-8 string is as follows:

StrConv("hello world",vbFromUnicode)

So put simply:

Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum

No special COM objects required

When should a class be Comparable and/or Comparator?

Comparable lets a class implement its own comparison:

  • it's in the same class (it is often an advantage)
  • there can be only one implementation (so you can't use that if you want two different cases)

By comparison, Comparator is an external comparison:

  • it is typically in a unique instance (either in the same class or in another place)
  • you name each implementation with the way you want to sort things
  • you can provide comparators for classes that you do not control
  • the implementation is usable even if the first object is null

In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.

As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(

  • Comparable<Object> lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.
  • Comparable<Itself> is very strict on the contrary.

Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).

not finding android sdk (Unity)

I solved the problem by uninstalling JDK 9.

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Page scroll when soft keyboard popped up

well the simplest answer i tried is just remove your code which makes the activity go full screen .I had a code like this which was responsible for making my activity go fullscreen :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

i just removed my code and it works completely fine although if you want to achieve this with your fullscreen on then you'll have to try some other methods

Outlets cannot be connected to repeating content iOS

Or you don't have to use IBOutlet to refer to the object in the view. You can give the Label in the tableViewCell a Tag value, for example set the Tag to 123 (this can be done by the attributes inspector). Then you can access the label by

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "someID", for: indexPath)

    let label = cell.viewWithTag(123) as! UILabel //refer the label by Tag

    switch indexPath.row {
    case 0:
        label.text = "Hello World!"
    default:
        label.text = "Default"
    }
    return cell 
}

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are a couple of things that you need to check related to this.

Whenever there is an error like this thrown related to making a secure connection, try running a script like the one below in Powershell with the name of the machine or the uri (like "www.google.com") to get results back for each of the different protocol types:

 function Test-SocketSslProtocols {
    
    [CmdletBinding()] 
    param(
        [Parameter(Mandatory=$true)][string]$ComputerName,
        [int]$Port = 443,
        [string[]]$ProtocolNames = $null
        )

    #set results list    
    $ProtocolStatusObjArr = [System.Collections.ArrayList]@()


    if($ProtocolNames -eq $null){

        #if parameter $ProtocolNames empty get system list
        $ProtocolNames = [System.Security.Authentication.SslProtocols] | Get-Member -Static -MemberType Property | Where-Object { $_.Name -notin @("Default", "None") } | ForEach-Object { $_.Name }

    }
 
    foreach($ProtocolName in $ProtocolNames){

        #create and connect socket
        #use default port 443 unless defined otherwise
        #if the port specified is not listening it will throw in error
        #ensure listening port is a tls exposed port
        $Socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
        $Socket.Connect($ComputerName, $Port)

        #initialize default obj
        $ProtocolStatusObj = [PSCustomObject]@{
            Computer = $ComputerName
            Port = $Port 
            ProtocolName = $ProtocolName
            IsActive = $false
            KeySize = $null
            SignatureAlgorithm = $null
            Certificate = $null
        }

        try {

            #create netstream
            $NetStream = New-Object System.Net.Sockets.NetworkStream($Socket, $true)

            #wrap stream in security sslstream
            $SslStream = New-Object System.Net.Security.SslStream($NetStream, $true)
            $SslStream.AuthenticateAsClient($ComputerName, $null, $ProtocolName, $false)
         
            $RemoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$SslStream.RemoteCertificate
            $ProtocolStatusObj.IsActive = $true
            $ProtocolStatusObj.KeySize = $RemoteCertificate.PublicKey.Key.KeySize
            $ProtocolStatusObj.SignatureAlgorithm = $RemoteCertificate.SignatureAlgorithm.FriendlyName
            $ProtocolStatusObj.Certificate = $RemoteCertificate

        } 
        catch  {

            $ProtocolStatusObj.IsActive = $false
            Write-Error "Failure to connect to machine $ComputerName using protocol: $ProtocolName."
            Write-Error $_

        }   
        finally {
            
            $SslStream.Close()
        
        }

        [void]$ProtocolStatusObjArr.Add($ProtocolStatusObj)

    }

    Write-Output $ProtocolStatusObjArr

}

Test-SocketSslProtocols -ComputerName "www.google.com"

It will try to establish socket connections and return complete objects for each attempt and successful connection.

After seeing what returns, check your computer registry via regedit (put "regedit" in run or look up "Registry Editor"), place

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

in the filepath and ensure that you have the appropriate TLS Protocol enabled for whatever server you're trying to connect to (from the results you had returned from the scripts). Adjust as necessary and then reset your computer (this is required). Try connecting with the powershell script again and see what results you get back. If still unsuccessful, ensure that the algorithms, hashes, and ciphers that need to be enabled are narrowing down what needs to be enabled (IISCrypto is a good application for this and is available for free. It will give you a real time view of what is enabled or disabled in your SChannel registry where all these things are located).

Also keep in mind the Windows version, DotNet version, and updates you have currently installed because despite a lot of TLS options being enabled by default in Windows 10, previous versions required patches to enable the option.

One last thing: TLS is a TWO-WAY street (keep this in mind) with the idea being that the server's having things available is just as important as the client. If the server only offers to connect via TLS 1.2 using certain algorithms then no client will be able to connect with anything else. Also, if the client won't connect with anything else other than a certain protocol or ciphersuite the connection won't work. Browsers are also something that need to be taken into account with this because of their forcing errors on HTTP2 for anything done with less than TLS 1.2 DESPITE there NOT actually being an error (they throw it to try and get people to upgrade but the registry settings do exist to modify this behavior).

is there a tool to create SVG paths from an SVG file?

Open the SVG with you text editor. If you have some luck the file will contain something like:

<path d="M52.52,26.064c-1.612,0-3.149,0.336-4.544,0.939L43.179,15.89c-0.122-0.283-0.337-0.484-0.58-0.637  c-0.212-0.147-0.459-0.252-0.738-0.252h-8.897c-0.743,0-1.347,0.603-1.347,1.347c0,0.742,0.604,1.345,1.347,1.345h6.823  c0.331,0.018,1.022,0.139,1.319,0.825l0.54,1.247l0,0L41.747,20c0.099,0.291,0.139,0.749-0.604,0.749H22.428  c-0.857,0-1.262-0.451-1.434-0.732l-0.11-0.221v-0.003l-0.552-1.092c0,0,0,0,0-0.001l-0.006-0.011l-0.101-0.2l-0.012-0.002  l-0.225-0.405c-0.049-0.128-0.031-0.337,0.65-0.337h2.601c0,0,1.528,0.127,1.57-1.274c0.021-0.722-0.487-1.464-1.166-1.464  c-0.68,0-9.149,0-9.149,0s-1.464-0.17-1.549,1.369c0,0.688,0.571,1.369,1.379,1.369c0.295,0,0.7-0.003,1.091-0.007  c0.512,0.014,1.389,0.121,1.677,0.679l0,0l0.117,0.219c0.287,0.564,0.751,1.473,1.313,2.574c0.04,0.078,0.083,0.166,0.126,0.246  c0.107,0.285,0.188,0.807-0.208,1.483l-2.403,4.082c-1.397-0.606-2.937-0.947-4.559-0.947c-6.329,0-11.463,5.131-11.463,11.462  S5.15,48.999,11.479,48.999c5.565,0,10.201-3.968,11.243-9.227l5.767,0.478c0.235,0.02,0.453-0.04,0.654-0.127  c0.254-0.043,0.507-0.128,0.713-0.311l13.976-12.276c0.192-0.164,0.874-0.679,1.151-0.039l0.446,1.035  c-2.659,2.099-4.372,5.343-4.372,8.995c0,6.329,5.131,11.461,11.462,11.461c6.329,0,11.464-5.132,11.464-11.461  C63.983,31.196,58.849,26.064,52.52,26.064z M11.479,46.756c-4.893,0-8.861-3.968-8.861-8.861s3.969-8.859,8.861-8.859  c1.073,0,2.098,0.201,3.051,0.551l-4.178,7.098c-0.119,0.202-0.167,0.418-0.183,0.633c-0.003,0.022-0.015,0.036-0.016,0.054  c-0.007,0.091,0.02,0.172,0.03,0.258c0.008,0.054,0.004,0.105,0.018,0.158c0.132,0.559,0.592,1,1.193,1.05l8.782,0.727  C19.397,43.655,15.802,46.756,11.479,46.756z M15.169,36.423c-0.003-0.002-0.003-0.002-0.006-0.002  c-1.326-0.109-0.482-1.621-0.436-1.704l2.224-3.78c1.801,1.418,3.037,3.515,3.32,5.908L15.169,36.423z M25.607,37.285l-2.688-0.223  c-0.144-3.521-1.87-6.626-4.493-8.629l1.085-1.842c0.938-1.593,1.756,0.001,1.756,0.001l0,0c1.772,3.48,3.65,7.169,4.745,9.331  C26.012,35.924,26.746,37.379,25.607,37.285z M43.249,24.273L30.78,35.225c0,0.002,0,0.002,0,0.002  c-1.464,1.285-2.177-0.104-2.188-0.127l-5.297-10.517l0,0c-0.471-0.936,0.41-1.062,0.805-1.073h17.926c0,0,1.232-0.012,1.354,0.267  v0.002C43.458,23.961,43.473,24.077,43.249,24.273z M52.52,46.745c-4.891,0-8.86-3.968-8.86-8.858c0-2.625,1.146-4.976,2.962-6.599  l2.232,5.174c0.421,0.977,0.871,1.061,0.978,1.065h0.023h1.674c0.9,0,0.592-0.913,0.473-1.199l-2.862-6.631  c1.043-0.43,2.184-0.672,3.381-0.672c4.891,0,8.861,3.967,8.861,8.861C61.381,42.777,57.41,46.745,52.52,46.745z" fill="#241F20"/>

The d attribute is what you are looking for.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

I recommend not to use one of those methods as is. Write your own function which does the right thing.

MDN has given a good example on url encoding shown below.

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);

console.log(header); 
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            //  so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

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

Use this cmd to display the packages in your device (for windows users)

adb shell pm list packages

then you can delete completely the package with the following cmd

adb uninstall com.example.myapp

How to fix homebrew permissions?

This solved the issue fore me.

sudo chown -R "$USER":admin /Users/$USER/Library/Caches/Homebrew
sudo chown -R "$USER":admin /usr/local

Set multiple system properties Java command line

Instead of passing the properties as an argument, you may use a .properties for storing them.

How to redirect to previous page in Ruby On Rails?

In your edit action, store the requesting url in the session hash, which is available across multiple requests:

session[:return_to] ||= request.referer

Then redirect to it in your update action, after a successful save:

redirect_to session.delete(:return_to)

What's the difference between Cache-Control: max-age=0 and no-cache?

By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.

This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.

I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.

I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.

Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.

It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.

User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.

This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.

Which .NET Dependency Injection frameworks are worth looking into?

I use Simple Injector:

Simple Injector is an easy, flexible and fast dependency injection library that uses best practice to guide your solutions toward the pit of success.

scp from Linux to Windows

If you want to copy paste files from Unix to Windows and Windows to Unix just use filezilla with port 22.

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

How do I get an OAuth 2.0 authentication token in C#

I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken and we get additional features like Token Cache out-of-the-box. From the documentation:

Why use ADAL.NET ?

ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.

Here is the code snippet:

    // Import Nuget package: Microsoft.Identity.Client
    public class AuthenticationService
    {
         private readonly List<string> _scopes;
         private readonly IConfidentialClientApplication _app;

        public AuthenticationService(AuthenticationConfiguration authentication)
        {

             _app = ConfidentialClientApplicationBuilder
                         .Create(authentication.ClientId)
                         .WithClientSecret(authentication.ClientSecret)
                         .WithAuthority(authentication.Authority)
                         .Build();

           _scopes = new List<string> {$"{authentication.Audience}/.default"};
       }

       public async Task<string> GetAccessToken()
       {
           var authenticationResult = await _app.AcquireTokenForClient(_scopes) 
                                                .ExecuteAsync();
           return authenticationResult.AccessToken;
       }
   }

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

SQL 'LIKE' query using '%' where the search criteria contains '%'

You need to escape it: on many databases this is done by preceding it with backslash, \%.

So abc becomes abc\%.

Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How do I merge dictionaries together in Python?

Trey Hunner has a nice blog post outlining several options for merging multiple dictionaries, including (for python3.3+) ChainMap and dictionary unpacking.

How to generate a range of numbers between two numbers?

If you don't have a problem installing a CLR assembly in your server a good option is writing a table valued function in .NET. That way you can use a simple syntax, making it easy to join with other queries and as a bonus won't waste memory because the result is streamed.

Create a project containing the following class:

using System;
using System.Collections;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

namespace YourNamespace
{
   public sealed class SequenceGenerator
    {
        [SqlFunction(FillRowMethodName = "FillRow")]
        public static IEnumerable Generate(SqlInt32 start, SqlInt32 end)
        {
            int _start = start.Value;
            int _end = end.Value;
            for (int i = _start; i <= _end; i++)
                yield return i;
        }

        public static void FillRow(Object obj, out int i)
        {
            i = (int)obj;
        }

        private SequenceGenerator() { }
    }
}

Put the assembly somewhere on the server and run:

USE db;
CREATE ASSEMBLY SqlUtil FROM 'c:\path\to\assembly.dll'
WITH permission_set=Safe;

CREATE FUNCTION [Seq](@start int, @end int) 
RETURNS TABLE(i int)
AS EXTERNAL NAME [SqlUtil].[YourNamespace.SequenceGenerator].[Generate];

Now you can run:

select * from dbo.seq(1, 1000000)

Alter table add multiple columns ms sql

Take out the parentheses and the curly braces, neither are required when adding columns.

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

What do >> and << mean in Python?

12 << 2

48

Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".

48 >> 2

12

The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".

Apache2: 'AH01630: client denied by server configuration'

For me, all proposed solutions won't worked. This can help, if you use cgi, fastcig or fpm as proxy you have to add a location in your vhost to avoid this problem. This allows 404 to be passthrough proxy.

<Location />
require all granted
</Location>

Java LinkedHashMap get first or last entry

public static List<Fragment> pullToBackStack() {
    List<Fragment> fragments = new ArrayList<>();
    List<Map.Entry<String, Fragment>> entryList = new ArrayList<>(backMap.entrySet());
    int size = entryList.size();
    if (size > 0) {
        for (int i = size - 1; i >= 0; i--) {// last Fragments
            fragments.add(entryList.get(i).getValue());
            backMap.remove(entryList.get(i).getKey());
        }
        return fragments;
    }
    return null;
}

Fastest way to extract frames using ffmpeg?

This worked for me

ffmpeg -i file.mp4 -vf fps=1 %d.jpg

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How is a tag different from a branch in Git? Which should I use, here?

The Git Parable explains how a typical DVCS gets created and why their creators did what they did. Also, you might want to take a look at Git for Computer Scientist; it explains what each type of object in Git does, including branches and tags.

Spring Boot yaml configuration for a list of strings

use comma separated values in application.yml

ignoreFilenames: .DS_Store, .hg

java code for access

@Value("${ignoreFilenames}")    
String[] ignoreFilenames

It is working ;)

Simple 3x3 matrix inverse code (C++)

# include <conio.h>
# include<iostream.h>

const int size = 9;

int main()
{
    char ch;

    do
    {
        clrscr();
        int i, j, x, y, z, det, a[size], b[size];

        cout << "           **** MATRIX OF 3x3 ORDER ****"
             << endl
             << endl
             << endl;

        for (i = 0; i <= size; i++)
            a[i]=0;

        for (i = 0; i < size; i++)
        {
            cout << "Enter "
                 << i + 1
                 << " element of matrix=";

            cin >> a[i]; 

            cout << endl
                 <<endl;
        }

        clrscr();

        cout << "your entered matrix is "
             << endl
             <<endl;

        for (i = 0; i < size; i += 3)
            cout << a[i]
                 << "  "
                 << a[i+1]
                 << "  "
                 << a[i+2]
                 << endl
                 <<endl;

        cout << "Transpose of given matrix is"
             << endl
             << endl;

        for (i = 0; i < 3; i++)
            cout << a[i]
                 << "  "
                 << a[i+3]
                 << "  "
                 << a[i+6]
                 << endl
                 << endl;

        cout << "Determinent of given matrix is = ";

        x = a[0] * (a[4] * a[8] -a [5] * a[7]);
        y = a[1] * (a[3] * a[8] -a [5] * a[6]);
        z = a[2] * (a[3] * a[7] -a [4] * a[6]);
        det = x - y + z;

        cout << det 
             << endl
             << endl
             << endl
             << endl;

        if (det == 0)
        {
            cout << "As Determinent=0 so it is singular matrix and its inverse cannot exist"
                 << endl
                 << endl;

            goto quit;
        }

        b[0] = a[4] * a[8] - a[5] * a[7];
        b[1] = a[5] * a[6] - a[3] * a[8];
        b[2] = a[3] * a[7] - a[4] * a[6];
        b[3] = a[2] * a[7] - a[1] * a[8];
        b[4] = a[0] * a[8] - a[2] * a[6];
        b[5] = a[1] * a[6] - a[0] * a[7];
        b[6] = a[1] * a[5] - a[2] * a[4];
        b[7] = a[2] * a[3] - a[0] * a[5];
        b[8] = a[0] * a[4] - a[1] * a[3];

        cout << "Adjoint of given matrix is"
             << endl
             << endl;

        for (i = 0; i < 3; i++)
        {
            cout << b[i]
                 << "  "
                 << b[i+3]
                 << "  "
                 << b[i+6]
                 << endl
                 <<endl;
        }

        cout << endl
             <<endl;

        cout << "Inverse of given matrix is "
             << endl
             << endl
             << endl;

        for (i = 0; i < 3; i++)
        {
            cout << b[i]
                 << "/"
                 << det
                 << "  "
                 << b[i+3]
                 << "/" 
                 << det
                 << "  "
                 << b[i+6]
                 << "/" 
                 << det
                 << endl
                  <<endl;
        }

        quit:

        cout << endl
             << endl;

        cout << "Do You want to continue this again press (y/yes,n/no)";

        cin >> ch; 

        cout << endl
             << endl;
    } /* end do */

    while (ch == 'y');
    getch ();

    return 0;
}

How to handle iframe in Selenium WebDriver using java

You have to get back out of the Iframe with the following code:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

hope that helps

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Based on this reference, the next approach worked for me:

// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017" 
var formatInfo = new DateTimeFormatInfo()
{
     ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);

Unity Scripts edited in Visual studio don't provide autocomplete

There is no auto-completion because the script says "Miscellaneous Files" instead of the of the name of the Project. Take a look at the image below that came from the video in your question:

enter image description here

The "Miscellaneous Files" message can happen for many reasons:

  1. It can happen when you open your Unity C# file from another folder instead of opening it from Unity Editor.

  2. This can also happen because Unity crashed while Visual Studio is still open therefore corrupting some files.

  3. It can happen because Unity was closed then re-opened but is no longer connected to Visual Studio. When Visual Studio is opened you get "Miscellaneous Files" and no auto-completion.

  4. This can happen when Visual Studio Tools for unity is not installed.

  5. When you create a script from Unity then quickly open it before Unity finish processing it or before the round icon animation stuff finish animating.


Most of the times, restarting Unity and Visual Studio should fix this.

I can't tell which one is causing the problem but I will cover the most likely solution to fix this.

Fix Part 1:

  1. Download and Install Visual Studio Tools for unity from this link. Do this while Unity and Visual Studio are both closed.

  2. From Unity Editor, go to Edit ? Preferences... ? External Tools. On the External Script Editor drop down menu, change that to Visual Studio 2015.

    enter image description here


Fix Part 2:

If newly created C# files are coming up as Miscellaneous then follow the instruction below:

  1. From Visual Studio, go to Tools ? Options... ? Tools for Unity ? Miscellaneous. Under Show connectivity icon, set it to true then restart Visual Studio.

    enter image description here

  2. When you re-start, connection icon should now be available in Visual Studio. Click it then choose the Unity instance to connect to. The red 'x' icon should now turn into a brown checkmark icon. Now, when you create a new C# file in Unity, it should open without saying Miscellaneous.

    enter image description here


Fix Part 3:

Still not fixed?

Re-import project then open C# Project.

  1. Close Visual Studio.

  2. From Unity, re-import project by going to Assets ? Reimport All.

    enter image description here

  3. Now, open the project in Visual Studio by going to Assets ? Open C# Project. This will reload the project and fix possible solution file problems.

    enter image description here


Fix Part 4:

Still not fixed?

Fix each C# file individually.

  1. Click on Show All Files icon.

    enter image description here

  2. Select the script that doesn't do auto-complete then right-click and select Include In Project.

    enter image description here


Fix Part 5:

Not fixed yet?

Credit goes to chrisvarnz for this particular solution which seems to have worked for multiple people.

  1. Close Visual Studio

  2. Go your project directory and delete all the generated Visual Studio files.

    These are the files extensions to delete:

    • .csproj
    • .user
    • .sln

    Example:

    Let's say that the name of your Project is called Target_Shoot, these are what the files to delete should look like:

    • Target_Shoot.csproj
    • Target_Shoot.Editor.csproj
    • Target_Shoot.Editor.csproj.user
    • Target_Shoot.Player.csproj
    • Target_Shoot.Player.csproj.user
    • Target_Shoot.sln

    Do not delete anything else.

  3. Double click on the script again from Unity which should generate new Visual Studio file then open Visual Studio. This may solve your problem.


Fix Part 6:

If not working, check if you are having this error:

The "GetReferenceNearestTargetFrameworkTask" task was not found

  1. Install Nuget PackageManager from here.

  2. Restart Visual Visual.

See this answer for more information.

The view didn't return an HttpResponse object. It returned None instead

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

above code can be changed to

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

PowerShell: Run command from script's directory

If you're calling native apps, you need to worry about [Environment]::CurrentDirectory not about PowerShell's $PWD current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.

In a script, you can do this:

$CWD = [Environment]::CurrentDirectory

Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
##  Your script code calling a native executable
Pop-Location

# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD

There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.

Two notes about the reason why this is not set by PowerShell automatically:

  1. PowerShell can be multi-threaded. You can have multiple Runspaces (see RunspacePool, and the PSThreadJob module) running simultaneously withinin a single process. Each runspace has it's own $PWD present working directory, but there's only one process, and only one Environment.
  2. Even when you're single-threaded, $PWD isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).

If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:

[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

For me I was working under Ubuntu

The error disappeared if I use sudo with ng

sudo ng build
sudo ng serve

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

python BeautifulSoup parsing table

Here is working example for a generic <table>. (question links-broken)

Extracting the table from here countries by GDP (Gross Domestic Product).

htmltable = soup.find('table', { 'class' : 'table table-striped' })
# where the dictionary specify unique attributes for the 'table' tag

The tableDataText function parses a html segment started with tag <table> followed by multiple <tr> (table rows) and inner <td> (table data) tags. It returns a list of rows with inner columns. Accepts only one <th> (table header/data) in the first row.

def tableDataText(table):       
    rows = []
    trs = table.find_all('tr')
    headerow = [td.get_text(strip=True) for td in trs[0].find_all('th')] # header row
    if headerow: # if there is a header row include first
        rows.append(headerow)
        trs = trs[1:]
    for tr in trs: # for every table row
        rows.append([td.get_text(strip=True) for td in tr.find_all('td')]) # data row
    return rows

Using it we get (first two rows).

list_table = tableDataText(htmltable)
list_table[:2]

[['Rank',
  'Name',
  "GDP (IMF '19)",
  "GDP (UN '16)",
  'GDP Per Capita',
  '2019 Population'],
 ['1',
  'United States',
  '21.41 trillion',
  '18.62 trillion',
  '$65,064',
  '329,064,917']]

That can be easily transformed in a pandas.DataFrame for more advanced tools.

import pandas as pd
dftable = pd.DataFrame(list_table[1:], columns=list_table[0])
dftable.head(4)

pandas DataFrame html table output

Convert SQL Server result set into string

This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).

DECLARE @results VARCHAR(1000) = '' 
SELECT @results = @results + 
           ISNULL(CASE WHEN LEN(@results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz

select @results

How to convert timestamps to dates in Bash?

I use this when converting log files or monitoring them:

tail -f <log file> | gawk \
'{ printf strftime("%c", $1); for (i=2; i<NF; i++) printf $i " "; print $NF }'

How to iterate using ngFor loop Map containing key as string and values as map iteration

As people have mentioned in the comments keyvalue pipe does not retain the order of insertion (which is the primary purpose of Map).

Anyhow, looks like if you have a Map object and want to preserve the order, the cleanest way to do so is entries() function:

<ul>
    <li *ngFor="let item of map.entries()">
        <span>key: {{item[0]}}</span>
        <span>value: {{item[1]}}</span>
    </li>
</ul>

jQuery scroll() detect when user stops scrolling

Using jQuery throttle / debounce

jQuery debounce is a nice one for problems like this. jsFidlle

$(window).scroll($.debounce( 250, true, function(){
    $('#scrollMsg').html('SCROLLING!');
}));
$(window).scroll($.debounce( 250, function(){
    $('#scrollMsg').html('DONE!');
}));

The second parameter is the "at_begin" flag. Here I've shown how to execute code both at "scroll start" and "scroll finish".

Using Lodash

As suggested by Barry P, jsFiddle, underscore or lodash also have a debounce, each with slightly different apis.

$(window).scroll(_.debounce(function(){
    $('#scrollMsg').html('SCROLLING!');
}, 150, { 'leading': true, 'trailing': false }));

$(window).scroll(_.debounce(function(){
    $('#scrollMsg').html('STOPPED!');
}, 150));